本文共 722 字,大约阅读时间需要 2 分钟。
#includeconst int maxn = 110;int father[maxn];bool isRoot[maxn];void init(int n){ for(int i = 1; i <= n; i++) { father[i] = i; isRoot[i] = false; }}int findFather(int x){ while(x != father[x]) { x = father[x]; } return x;}void Union(int a, int b){ int faA = findFather(a); int faB = findFather(b); if(faA != faB) { father[faA] = faB; }}int main(){ int n, m, a, b; scanf("%d%d", &n, &m); init(n); for(int i = 0; i < m; i++) { scanf("%d%d", &a, &b); Union(a, b); } for(int i = 1; i <= n; i++) { isRoot[findFather(i)] = true; } int ans = 0; for(int i = 1; i <= n; i++) { ans += isRoot[i]; } printf("%d\n", ans); return 0;}
转载地址:http://hhtmi.baihongyu.com/