NOJ [1246] Virtual Friends

  • 问题描述
  • These days, you can do all sorts of things online. For example, you can use various websites to make virtual friends. For some people, growing their social network (their friends, their friends' friends, their friends' friends' friends, and so on), has become an addictive hobby. Just as some people collect stamps, other people collect virtual friends.

    Your task is to observe the interactions on such a website and keep track of the size of each person's network.

    Assume that every friendship is mutual. If Fred is Barney's friend, then Barney is also Fred's friend.

  • 输入
  • The first line of input contains one integer specifying the number of test cases to follow. Each test case begins with a line containing an integer F, the number of friendships formed, which is no more than 100 000. Each of the following F lines contains the names of two people who have just become friends, separated by a space. A name is a string of 1 to 20 letters (uppercase or lowercase).
  • 输出
  • Whenever a friendship is formed, print a line containing one integer, the number of people in the social network of the two people who have just become friends.

    这题题意就是并查集的思想,至于怎么存字符串,刚好学会了map,正好派用场
    逗比的我找错误找了半小时
    #include<stdio.h>
    #include<string.h>
    #include<map>
    #include<iterator>
    using namespace std;
    
    int father[100010];
    int a[100010];
    int find(int x)
    {
       if (father[x] == x) return x;
         father[x]=find(father[x]);
         return father[x];
    }
    
    void unit(int x,int y)
    {
    	int xx=find(x);
    	int yy=find(y);
    	if(xx!=yy)
    	{
    		 father[yy]=xx;
             a[xx]+=a[yy];
    	}
    }
      map<string,int>friends;
    int main()
    {
      int t,n;
     
      while(~scanf("%d",&t))
      {
        while(t--)
        {
          scanf("%d",&n);
          int i,j,cnt=0;
          int p,q;
          friends.clear();
          memset(a,0,sizeof(a));
          memset(father,0,sizeof(father));
          for(i=0;i<n;i++)
          { 
    	     char name1[22],name2[22];
            scanf("%s%s",name1,name2);
            if(friends[name1]==NULL)  //此人没出现过
            { 
    		   cnt++;
              friends[name1]+=cnt;
              father[friends[name1]]=friends[name1];
              a[father[cnt]]=1;
            }
    
            if(friends[name2]==NULL)
            {
    		  cnt++;
              friends[name2]+=cnt;
              father[friends[name2]]=friends[name2];
              a[father[cnt]]=1;
            }
            unit(friends[name1],friends[name2]);
            printf("%d\n",a[find(friends[name1])]);
          }
        }
      }
      return 0;
    }


你可能感兴趣的:(NOJ [1246] Virtual Friends)