#include<iostream> #include<cstring> using namespace std; int a[1000005]; int n,m,l,ci,di; int root(int x) //找到根节点 { int r = x; while(r != a[r]) r = a[r]; int i = x,j; while(i != r) //压缩路径 { j = a[i]; a[i] = r; i = j; } return r; } void mix(int x,int y) //混合 { int fx = root(x),fy = root(y); if(fx != fy) a[fy] = fx; //根节点的值覆盖 } int main() { int i,j,t1,t2; // memset(a,0,sizeof(a)); //过程中超时了,除去这一条就AC了 cin>>n>>m; for(i = 1;i <= n;i++) a[i] = i; for(i = 1;i <= m;i++) { cin>>ci>>di; mix(ci,di); } cin>>l; for(i = 1;i <= l;i++) { cin>>t1>>t2; if(root(t1) != root(t2)) cout<<"They aren‘t relative!"<<endl; else cout<<"They are relative!"<<endl; } return 0; }
这是自学的并查集,然后在oj上敲的题。有关并查集的学习可以百度。
-----15:44:28 2017-06-10
时间: 2024-10-18 18:53:38