1008 Airline Routes (35分)(C++)

Given a map of airline routes, you are supposed to check if a round trip can be planned between any pair of cities.

Input Specification:

Each input file contains one test case. For each case, the first line gives two positive integers N (2≤N≤10​4​​) and M (≤6N), which are the total number of cities (hence the cities are numbered from 1 to N) and the number of airline routes, respectively. Then M lines follow, each gives the information of a route in the format of the source city index first, and then the destination city index, separated by a space. It is guaranteed that the source is never the same as the destination.

After the map information, another positive integer K is given, which is the number of queries. Then K lines of queries follow, each contains a pair of distinct cities' indices.

Output Specification:

For each query, output in a line Yes if a round trip is possible, or No if not.

Sample Input:

12 19
3 4
1 3
12 11
5 9
6 2
3 2
10 7
9 1
7 12
2 4
9 5
2 6
12 4
11 10
4 8
8 12
11 8
12 7
1 5
20
11 4
12 7
3 6
2 3
5 3
3 9
4 3
8 3
8 10
10 11
7 8
7 1
9 5
1 9
2 6
3 1
3 12
7 3
6 9
6 8

Sample Output:

Yes
Yes
No
No
No
No
No
No
Yes
Yes
Yes
No
Yes
Yes
Yes
No
No
No
No
No

題目大意:給出n個點m個邊的有向圖,然後給出k對點,判斷每對是否是強連通分量

解題思路:tarjan算法

代碼:

#include <bits/stdc++.h>
using namespace std;
const int N = 10005;
vector<int> graph[N];
int tim, tp, cnt;
int dfn[N], low[N], stk[N], insk[N], blong[N];
stack<int> s;
void tarjan(int u){
	dfn[u] = low[u] = ++ tim;
	insk[u] = 1;
	stk[++tp] = u;
	for(int j = 0; j < graph[u].size(); ++ j){
		int v = graph[u][j];
		if(!dfn[v]){
			tarjan(v);
			low[u] = min(low[u], low[v]);
		}
		else if(insk[v])
			low[u] = min(low[u], dfn[v]);
	}
	if(dfn[u] == low[u]){
		int temp;
		++ cnt;
		do{
			temp = stk[tp--];
			insk[temp] = 0;
			blong[temp] = cnt;
		}while(temp != u);
	}
}
int main(){
	int n, m, k, a, b;
	scanf("%d %d", &n, &m);
	for(int i = 0; i < m; ++ i){
		scanf("%d %d", &a, &b);
		graph[a].push_back(b);
	}
	for(int i = 1; i <= n; ++ i )
		if(dfn[i] == 0)
			tarjan(i);
	scanf("%d", &k);
	for(int i = 0; i < k; ++ i){
		scanf("%d %d", &a, &b);
		printf("%s\n", blong[a] == blong[b] ? "Yes": "No");
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章