zoukankan      html  css  js  c++  java
  • hust 1259 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.

    样例输入

    1
    3
    Fred Barney
    Barney Betty
    Betty Wilma
    

    样例输出

    2
    3
    4

    又是一个并查集的模板题,并查集很牛,但是它不难
    #include<map>
    #include<cstdio>
    #include<cstring>
    #include<string>
    #include<iostream>
    #include<algorithm>
    using namespace std;
    
    map<string,int>people;
    string str1,str2;
    struct node
    {
        int root,num;
    }p[100001];
    
    void init()
    {
        people.clear();
        for (int i=0;i<=100000;i++)
        {
            p[i].num=1;
            p[i].root=i;
        }
    }
    
    int find(int x)
    {
        return x==p[x].root?x:p[x].root=find(p[x].root);
    }
    
    int main()
    {
        int n,m,t,x,y;
        cin>>t;
        while(t--)
        {
            init();
            m=1;
            cin>>n;
            for (int i=0;i<n;i++)
            {
                cin>>str1>>str2;
                if (!people[str1]) {people[str1]=m;x=m;m++;}
                else x=people[str1];
                if (!people[str2]) {people[str2]=m;y=m;m++;}
                else y=people[str2];
                x=find(x);
                y=find(y);
                if (x!=y)
                {
                    p[x].root=y;
                    p[y].num+=p[x].num;
                    cout<<p[y].num<<endl;
                }
                else cout<<p[x].num<<endl;
            }
        }
        return 0;
    }
    至少做到我努力了
  • 相关阅读:
    jquery笔记
    css选择器
    Linq 巧用 Max,Sum
    Linq Aggregate
    Linq 对象的比较 Contains,Max
    Linq SelectMany 交叉连接
    JQ 标签相关知识
    C# HttpClient设置cookies的两种办法 (转发)
    使用 HttpClient 请求 Web Api
    MySQL 避免重复数据的批量插入与批量更新
  • 原文地址:https://www.cnblogs.com/chensunrise/p/3723180.html
Copyright © 2011-2022 走看看