Input测试输入包含若干测试用例。每个测试用例的第1行给出两个正整数,分别是城镇数目N ( < 1000 )和道路数目M;随后的M行对应M条道路,每行给出一对正整数,分别是该条道路直接连通的两个城镇的编号。为简单起见,城镇从1到N编号。 注意:两个城市之间可以有多条道路相通,也就是说 3 3 1 2 1 2 2 1 这种输入也是合法的 当N为0时,输入结束,该用例不被处理。 Output对每个测试用例,在1行里输出最少还需要建设的道路数目。 Sample Input
4 2 1 3 4 3 3 3 1 2 1 3 2 3 5 2 1 2 3 5 999 0 0Sample Output
1 0 2 998 Huge input, scanf is recommended.Hint
Hint并查集裸题。。查用路径压缩效率高,并遵循向左原则,注意//一定是find(i)不是f[i] #include<stdio.h> int f[1005]; int find(int x) { return f[x]==x?x:f[x]=find(f[x]); //路径压缩 } void join(int x,int y) { int fx=find(x),fy=find(y); if(fx!=fy) f[fy]=fx; //向左原则 } int main() { int n,m,x,y,c,i; while(scanf("%d",&n)&&n!=0){ scanf("%d",&m); for(i=1;i<=n;i++){ f[i]=i; } for(i=1;i<=m;i++){ scanf("%d%d",&x,&y); join(x,y); } c=0; for(i=1;i<=n;i++){ if(find(i)==i) c++; //WA教训。。一定是find(i)不是f[i] } printf("%d\n",c-1); } return 0; }
转载于:https://www.cnblogs.com/yzm10/p/7194216.html
