hdu Virtual Friends

  这题是一个很简单额并查集的题目,首先第一步是要用map将字符串映射为整型,这样方便后面的处理,然后就是用一个rank[]数组来记录每个朋友圈的人数。之后就是简单的并查集操作了。

这里给出一组测试案例:

1
6
Fred Barney
Barney Betty
Betty Wilma
AAAAA BBBBB
AAAA  BBBBB
AAAA Fred

输出结果应是:
2
3
4
2
3
7
代码如下:
复制代码
#include"iostream"
#include"stdio.h"
#include"algorithm"
#include"string"
#include"string.h"
#include"cmath"
#include"ctype.h"
#include"map"
#include"vector"
#include"queue"
#include"stack"
using namespace std;
const int mx=100005;
int num_nest;
int F;
map<string,int>name;
int fa[2*mx];
int Rank[2*mx];

void Set()
{
    for(int i=0;i<2*F;i++)
     {
         fa[i]=i;
         Rank[i]=1;
     }
}

int Find(int x)
{
    int t1,t2=x;
    while(t2!=fa[t2]) t2=fa[t2];
    while(x!=t2)//可以减小时间复杂度
    {
        t1=fa[x];
        fa[x]=t2;
        x=t1;
    }
    return t2;
}

void Union(int x,int y)
{
    int fx=Find(x);
    int fy=Find(y);
    if(fx!=fy)
    {
      fa[fx]=fy;
      Rank[fy]+=Rank[fx];
      Rank[fx]=Rank[fy];

    }
}

bool is_exist(const string &str)//查找map中是否已存在该元素
{
    return name.find(str)== name.end();
}

void IO()
{
    while(scanf("%d",&num_nest)==1)
    {
        while(num_nest--)
        {
            string name1,name2;
            int cnt=0,id1,id2;
            name.clear();
            scanf("%d",&F);
            Set();
            getchar();
            while(F--)
            {
                cin>>name1;
                if(is_exist(name1))
                {
                    name.insert(pair<string,int>(name1,cnt));
                    id1=cnt;
                    cnt++;
                }
                else
                    id1=(name.find(name1))->second;
                cin>>name2;
                if(is_exist(name2))
                {
                    name.insert(pair<string,int>(name2,cnt));
                    id2=cnt;
                    cnt++;
                }
                else
                   id2=(name.find(name2))->second;
                Union(id1,id2);
                int fid1=Find(id1);
                printf("%d\n",Rank[fid1]);
            }
        }
    }
}
int main()
{
    IO();
    return 0;
}
View Code
复制代码

 

posted @   Run_For_Love  阅读(187)  评论(0编辑  收藏  举报
编辑推荐:
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
阅读排行:
· 官方的 MCP C# SDK:csharp-sdk
· 一款 .NET 开源、功能强大的远程连接管理工具,支持 RDP、VNC、SSH 等多种主流协议!
· 提示词工程师自白:我如何用一个技巧解放自己的生产力
· 一文搞懂MCP协议与Function Call的区别
· 如何不购买域名在云服务器上搭建HTTPS服务
点击右上角即可分享
微信分享提示