题目链接:https://www.luogu.org/problemnew/show/P1536
并查集的运用,可以用生成树的思想,就是n个点生成一棵树需要n-1条边。这样我们先把已有的路连接到一个并查集,并记录数目,最后用n-1减这个数即可。输入n,m时注意一个一个输,这样便于判断n==0
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 using namespace std; 5 const int maxn = 1001; 6 int fa[maxn], n, m, tot = 0, ans[100001]; 7 struct edge{ 8 int u,v; 9 }e[1000001]; 10 int find(int x) 11 { 12 return fa[x]==x?x:fa[x]=find(fa[x]); 13 } 14 int main() 15 { 16 int k = 0; 17 while(scanf("%d",&n)) 18 { 19 if(n == 0) 20 { 21 for(int i = 1; i <= k; i++) 22 printf("%d\n",ans[i]); 23 return 0; 24 } 25 scanf("%d",&m); 26 tot = 0; 27 k++; 28 for(int i = 1; i <= n; i++) 29 fa[i] = i; 30 for(int i = 1; i <= m; i++) 31 { 32 scanf("%d%d",&e[i].u, &e[i].v); 33 { 34 int x = find(e[i].u); 35 int y = find(e[i].v); 36 if(x!=y) 37 { 38 fa[y] = x; tot++; 39 } 40 } 41 } 42 ans[k] = n - tot -1; 43 } 44 45 }