链接:http://xcacm.hfut.edu.cn/problem.php?id=1234
以后关于字符的输入都用cin吧,换成scanf居然wa了
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 #include <map> 6 #include <string> 7 #include <set> 8 #define Max 10005 9 using namespace std; 10 int pre[Max],Rank[Max]; 11 int sum; 12 void init() 13 { 14 for(int i=0;i<Max;i++) 15 pre[i]=i; 16 return; 17 } 18 int find(int x) 19 { 20 if(pre[x]==x) 21 return x; 22 return pre[x]=find(pre[x]); 23 } 24 int unite(int a,int b) 25 { 26 int x=find(a); 27 int y=find(b); 28 if(Rank[x]==Rank[y]) 29 return 0; 30 sum--; 31 if(Rank[x]<Rank[y]) 32 pre[y]=x; 33 else 34 pre[x]=y; 35 return 0; 36 } 37 int main() 38 { 39 int n,m; 40 char ch; 41 string s,a,b; 42 map<string,int> u; 43 //freopen("in.txt","r",stdin); 44 //freopen("out.txt","w",stdout); 45 while(scanf("%d",&n)!=EOF) 46 { 47 sum=n; 48 u.clear(); 49 init(); 50 for(int i=0;i<n;i++) 51 { 52 cin>>s; 53 u[s]=i+1; 54 Rank[i+1]=i+1; 55 } 56 cin>>m; 57 for(int i=0;i<m;i++) 58 { 59 cin>>ch; 60 if(ch=='a') 61 { 62 cin>>a>>b; 63 unite(u[a],u[b]); 64 } 65 else if (ch=='q') 66 { 67 cin>>a; 68 int r=find(u[a]); 69 printf("%d ",Rank[r]); 70 } 71 else if (ch=='t') 72 printf("%d ",sum); 73 } 74 } 75 return 0; 76 }