并查集
Posted Gssol
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了并查集相关的知识,希望对你有一定的参考价值。
#include<bits/stdc++.h> using namespace std; int pre[2000]; int find1(int x) { int r=x; while(pre[r]!=r) { r=pre[r]; } return r; } void join(int x,int y) { int fx=find1(x); int fy=find1(y); if(fx!=fy) pre[fy]=fx; } int main() { int n,m,k,a,b; int t; cin>>t; while(t--) { for(int i=1;i<1200;i++) pre[i]=i; cin>>n>>m; while(m--) { cin>>a>>b; if(a>b) swap(a,b); join(a,b); } int ans=0; for(int i=1;i<=n;i++) { if(find1(i)==i) { ans++; } } cout<<ans<<endl; } return 0; }
以上是关于并查集的主要内容,如果未能解决你的问题,请参考以下文章