• 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;
    }
    至少做到我努力了
  • 相关阅读:
    实战-rsync+inotify打造文件实时备份
    实战-Mysql5.6.36脚本编译安装及初始化
    实战-CentOS6.8配置nfs服务
    CentOS7操作系统初始化
    docker搭建 SonarQube代码质量管理平台
    ubuntu 教程
    前端图表库
    WebSSH2安装过程可实现WEB可视化管理SSH工具
    devops 自动化平台网址
    AIops 智能运维平台
  • 原文地址:https://www.cnblogs.com/chensunrise/p/3723180.html
Copyright © 2020-2023  润新知