T1008 Airline Routes (35 point(s))
文章目录
题干
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≤104) 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
题目大意
求出有向图中的所有强连通分量。
题目限制条件
- 时间限制:400ms
- 内存限制:64MB
本题考察知识点
- 强连通分量算法
- 并查集
解题思路
强连通分量算法模板题,求解强连通分量的算法请参考此处
AC代码
#include "bits/stdc++.h"
using namespace std;
int N, M, K;
#define maxn 10005
vector<vector<int>> v_graph;
int father[maxn];
int get_father(int n) {
if (n == father[n])return n;
else return father[n] = get_father(father[n]);
}
void unite(int a, int b) {
int fa = get_father(a), fb = get_father(b);
if (fa != fb) {
father[fb] = fa;
}
}
void dfs(int cur) {
static int tdx = 0;
static int dfn[maxn] = {0};
static int low[maxn] = {0};
static bool in_stack[maxn] = {false};
static stack<int> stk;
dfn[cur] = low[cur] = ++tdx;
stk.push(cur);
in_stack[cur] = true;
for (int nxt: v_graph[cur]) {
if (!in_stack[nxt] && dfn[nxt] == 0) {
dfs(nxt);
low[cur] = min(low[cur], low[nxt]);
} else if (in_stack[nxt] && dfn[nxt] != 0) {
low[cur] = min(low[cur], dfn[nxt]);
}
}
if (dfn[cur] == low[cur]) {
while (1) {
auto T = stk.top();
stk.pop();
in_stack[T] = 0;
unite(cur, T);
if (T == cur)break;
}
}
}
int main() {
// freopen("in.txt", "r", stdin);
cin >> N >> M;
father[0] = 0;
v_graph.resize(N + 1);
for (int i = 1; i <= N; ++i) {
father[i] = i;
v_graph[0].push_back(i);
}
for (int i = 0; i < M; i++) {
int st, ed;
scanf("%d%d", &st, &ed);
v_graph[st].push_back(ed);
}
dfs(0);
cin >> K;
// for (int i = 0; i < N; ++i) {
// if (vis[i + 1])continue;
// dfs(i + 1);
// }
for (int i = 0; i < K; ++i) {
int v1, v2;
scanf("%d%d", &v1, &v2);
if (get_father(v1) == get_father(v2)) {
puts("Yes");
} else {
puts("No");
}
}
return 0;
}