标签:print desc stream whether width input rest oid ted
Time Limit: 5000MS | Memory Limit: 65536K | |
Total Submissions: 23262 | Accepted: 11464 |
Description
Input
Output
Sample Input
10 9 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 1 10 10 4 2 3 4 5 4 8 5 8 0 0
Sample Output
Case 1: 1 Case 2: 7
一道并查集基础题!
贴出两段代码!求解释?为什么第二段代码的时间有一千多毫秒!
#include <iostream> const int MAX = 50001; int p[MAX],rank[MAX]; int result; int findSet(int x) { if(x!=p[x]) p[x] = findSet(p[x]); return p[x]; } void Union(int x, int y) { if(x == y) return; result--; if(rank[x] > rank[y]) { p[y] = x; } else { p[x] = y; if(rank[x] == rank[y]) rank[y]++; } } int main() { int i,j; int s1,s2; int x,y; int n,m; int t = 1; while(true) { scanf("%d %d",&n,&m); if(n==0&&m==0) break; result = n; for(i = 1; i <= n; i++) { p[i] = i; rank[i] = 0; } for(i = 1; i <= m; i++) { scanf("%d %d",&x,&y); s1 = findSet(x); s2 = findSet(y); Union(s1,s2); } printf("Case %d: ",t++); printf("%d\n",result); } return 0; }<pre name="code" class="html">#include<iostream> using namespace std; const int MAX =50001; int father[MAX],rank[MAX]; int result; int Find_Set(int x) { if(x!=father[x]) father[x]=Find_Set(father[x]); return father[x]; } void Union_Set(int x,int y) { if(x==y)return ; result--; if(rank[x]>rank[y]) { father[y]=x; } else { father[x]=y; if(rank[x]==rank[y]) rank[y]++; } } int main() { int n,m; int i,x,y,s1,s2; int num=1; while(true) { cin>>n>>m; if(n==0&&m==0)break; result = n; for(i=1;i<=n;i++) { father[i]=i; rank[i]=0; } for(i=1;i<=m;i++) { cin>>x>>y; s1=Find_Set(x); s2=Find_Set(y); Union_Set(s1,s2); } cout<<"Case "<<num++<<": "<<result<<endl; } return 0; }
标签:print desc stream whether width input rest oid ted
原文地址:http://www.cnblogs.com/mthoutai/p/6910103.html