How Many Tables hdu-1213
思路:并查集之后找有几个集
#include<cstdio> #include<iostream> #include<algorithm> #include<cstring> #include<sstream> #include<cmath> #include<stack> #include<map> #include<cstdlib> #include <vector> #include<queue> using namespace std; const int INF = 0x3f3f3f3f; const int maxn = 1e3+5; int father[maxn]; void init(int n) { for(int i=1;i<=n;i++) father[i] = i; } int find(int x) { if(father[x] == x) return x; else return father[x] = find(father[x]); } void combine(int x,int y) { x = find(x); y = find(y); if(x != y) father[x] = y; } int main() { int t; scanf("%d",&t); while(t--) { int n,m; scanf("%d %d", &n,&m); init(n); for(int i=0;i<m;i++) { int a,b; scanf("%d%d",&a,&b); combine(a,b); } int res = 0; for(int i=1;i<=n;i++) if(i == find(i)) res++; printf("%d\n",res); } }
原文地址:https://www.cnblogs.com/smallhester/p/10316036.html
时间: 2024-11-02 10:44:18