C - Virtual Friends
网上搜了,好多c++里的东西啊
有思路不会做,真烦,还是好好学c++;
先把题和代码粘过来,过几天学c++好了再看
http://acm.hust.edu.cn/vjudge/contest/view.action?cid=94494#problem/C
#include<cstdio> #include<cstring> #include<cstdlib> #include<iostream> #include<map> #include<string> using namespace std; const int maxn=100003; int father[maxn]; int rank[maxn]; //初始化 void init( int n) { for(int i =0;i<=n ;i++) { father[i]=i; rank[i]=1; } } //搜索 int fin(int x) { int tem=x; while(x!=father[x]) { x=father[x]; } //进一步压缩 while(tem!=father[tem]) { tem=father[tem]; father[tem]=x; } return x; } void Union(int a,int b) { a=fin(a); b=fin(b); if(a!=b) { if(rank[a]<rank[b]) { rank[b]+=rank[a]; father[a]=b; } else { rank[a]+=rank[b]; father[b]=a; } } } map<string,int>sac; char aa[maxn][21],bb[maxn][21]; int main() { int t,n; while(scanf("%d",&t)!=EOF) { while(t--) { scanf("%d",&n); if(!sac.empty()) sac.clear(); int cnt=0; for(int i=0;i<n ;i++) { scanf("%s%s",aa[i],bb[i]); if(sac.find(aa[i])==sac.end()) sac[aa[i]]=++cnt; if(sac.find(bb[i])==sac.end()) { sac[bb[i]]=++cnt; } } init(cnt); for(int i=0;i<n;i++) { Union(sac[aa[i]],sac[bb[i]]); printf("%d\n",rank[fin(sac[aa[i]])]); } } } return 0; }