HDU3172 Virtual Friends
基础并查集~
#include<cstdio> #include<algorithm> #include<cstring> #include<unordered_map> #include<iostream> #include<string> using namespace std; const int maxn=1e6+14; unordered_map<string,int> pos; string s1,s2; int father[maxn],cnt,N,num[maxn]; void init () { for (int i=0;i<maxn;i++) father[i]=i; fill (num,num+maxn,1); cnt=0; pos.clear(); } int findfather (int x) { int a=x; while (x!=father[x]) x=father[x]; while (a!=father[a]) { int z=a; a=father[a]; father[z]=x; } return x; } void Union (int a,int b) { int faA=findfather(a); int faB=findfather(b); if (faA!=faB) father[faA]=faB,num[faB]+=num[faA]; } int main () { int T; while (~scanf("%d",&T)) { while (T--) { init (); scanf ("%d",&N); for (int i=0;i<N;i++) { cin>>s1>>s2; if (!pos[s1]) pos[s1]=++cnt; if (!pos[s2]) pos[s2]=++cnt; Union (pos[s1],pos[s2]); printf ("%d\n",num[findfather(pos[s1])]); } } } return 0; }