过程是模板 merge完后扫一下几个跟0同祖先节点就是答案了
#include <iostream> #include <string> #include <cstdio> #include <cmath> #include <cstring> #include <queue> #include <map> #include <set> #include <algorithm> using namespace std; const int MAX=30005; int father[MAX]; int findfather(int x) { while(x!=father[x]) x=father[x]; return x; } void merge(int x,int y) { x=findfather(x); y=findfather(y); if(x!=y) father[x]=y; } int main() { int n,m; while(scanf("%d%d",&n,&m),n||m) { int ans=0; for(int i=0;i<n;i++) father[i]=i; while(m--) { int k,fir,tmp; scanf("%d%d",&k,&fir); k--; while(k--) { scanf("%d",&tmp); merge(fir,tmp); } } int ex=findfather(0); for(int i=0;i<n;i++) if(findfather(i)==ex) ans++; printf("%d\n",ans); } return 0; }
(似乎这个时候代码还很丑)
时间: 2024-10-05 00:17:40