1 #include<iostream> 2 using namespace std; 3 //n-节点数 4 //m-边的数 5 //p-测试数 6 //给一幅图,判断两个点之间是否存在路径 7 8 int root[10001], n, m, p; 9 int find(int x) { 10 if (x == root[x])return x; 11 root[x] = find(root[x]); 12 return root[x]; 13 } 14 int main() { 15 cin >> n >> m >> p; 16 for (int i = 1; i <= n; ++i) { 17 root[i] = i; 18 } 19 for (int i = 1; i <= m; ++i) { 20 int x, y; 21 cin >> x >> y; 22 if (find(x) != find(y)) 23 root[find(x)] = find(y); 24 } 25 for (int i = 1; i <= p; i++) { 26 int x, y; 27 cin >> x >> y; 28 if (root[find(x)] == root[find(y)]) 29 cout << "YES" << endl; 30 else 31 cout << "NO" << endl; 32 } 33 return 0; 34 }
原文:https://www.cnblogs.com/zhang-le/p/13696231.html