ZCMU-1766-Virtual Friends

来源:互联网 发布:手机笔记软件 编辑:程序博客网 时间:2024/06/16 13:36

1766: Virtual Friends

Time Limit: 5 Sec  Memory Limit: 128 MB
Submit: 14  Solved: 6
[Submit][Status][Web Board]

Description

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.

Input

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).

Output

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.

Sample Input

1
3
Fred Barney
Barney Betty
Betty Wilma

Sample Output

2
3
4

【解析】
题意就是让你输出每一行所用有的朋友总数包括本身,所以其实就是并查集的应用了。但是因为输入的是字母,所以
我们需要用map来进行标记,来给它赋值,之后呢刚开始讲的通俗一点每个元素的老大都是他自己先进行初始化,然后
我们是开一个计算朋友总数的数组给他们都赋值为1,然后就是如果两个元素的老大不同的话就让他们的老大其中之一
做另一个人的老大,这个大概就是并查集的思想了。
#include <cstdio>#include <algorithm>#include <cstring>#include <iostream>#include<map>using namespace std;map<string,int>a;int pre[100010];int sum[100010];int find(int x){    int i=x;    while(i!=pre[i])        i=pre[i];//寻找老大    int j=x,k;    while(j!=i)    {        k=pre[j];//压缩路径的方法,大家可以模拟一下        pre[j]=i;        j=k;    }    return i;}int main(){    int t,i,n,m,x,y;    string s1,s2;    scanf("%d",&t);    while(t--)    {        m=1;        a.clear();        scanf("%d",&n);        for(i=1;i<=100000;i++)        {            pre[i]=i;            sum[i]=1;        }        for(i=0;i<n;i++)        {            cin>>s1>>s2;            if(a[s1]==0)            {                a[s1]=m;                m++;            }            if(a[s2]==0)            {                a[s2]=m;                m++;            }            x=find(a[s1]);            y=find(a[s2]);            if(x!=y)            {                pre[x]=y;//把x的老大设置成是y                sum[y]+=sum[x];//所有朋友的总数            }            printf("%d\n",sum[y]);        }    }    return 0;}

0 0
原创粉丝点击