spoj Help the Military Recruitment Office!

本文介绍了一种使用并查集数据结构解决特定类型问题的方法。问题涉及到名字与地点的对应关系,地点可能重定向,最终需要确定名字当前所属的具体位置。通过初始化并查集,读取输入数据,进行并查集操作,最后输出查询结果,实现了解决方案。

题意:给出名字和地方,地方会重定向,最后再给出名字,问现在属于哪里?

用并查集。

//#pragma comment(linker,"/STACK:1024000000,1024000000") 
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<vector>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<algorithm>
#include <stack>
using namespace std;
typedef long long lon;
const lon SZ=100010,INF=0x7FFFFFFF;
map<string,string> mp;
vector<string> ls;
int arr[SZ];

void init()
{
    for(int i=0;i<SZ;++i)arr[i]=i;
}

int find(int x)
{
    return arr[x]==x?x:arr[x]=find(arr[x]);
}

void adj(int x,int y)
{
    int rtx=find(x),rty=find(y);
    arr[rtx]=rty;
}

void work()
{
    mp.clear(),ls.clear();
    int n;
    cin>>n;
    for(int i=0;i<n;++i)
    {
        string name,bel;
        cin>>name>>bel;
        mp[name]=bel;
        ls.push_back(bel);
    }
    sort(ls.begin(),ls.end());
    ls.erase(unique(ls.begin(),ls.end()),ls.end());
    int m;
    cin>>m;
    init();
    for(int i=0;i<m;++i)
    {
        string src,dst;
        cin>>src>>dst;
        int a=lower_bound(ls.begin(),ls.end(),src)-ls.begin();
        int b=lower_bound(ls.begin(),ls.end(),dst)-ls.begin();
        adj(a,b);
    }
    int qnum;
    cin>>qnum;
    for(int i=0;i<qnum;++i)
    {
        string str;
        cin>>str;
        string src=mp[str];
        int id=lower_bound(ls.begin(),ls.end(),src)-ls.begin();
        id=find(id);
        cout<<str<<" "<<ls[id]<<endl;
    }
}

int main()
{
    std::ios::sync_with_stdio(0);
    //freopen("d:\\1.txt","w",stdout); 
    lon casenum;
    cin>>casenum;
    for(lon time=1;time<=casenum;++time)
    //for(;scanf("%d",&n)!=EOF;)
    {
        work();
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/gaudar/p/9751554.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值