我是靠谱客的博主 精明大树,最近开发中收集的这篇文章主要介绍ACdream 1056并查集+map,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

链接:http://acdream.info/problem?pid=1056

Problem Description

As the leader of the Evil League of Evil, Bad Horse has a lot of problems to deal with.

Most recently, there have been far too many arguments and far too much backstabbing in the League, so much so that Bad Horse has decided to split the league into two departments in order to separate troublesome members.

Being the Thoroughbred of Sin, Bad Horse isn't about to spend his valuable time figuring out how to split the League members by himself.

That what he's got you -- his loyal henchman -- for.

Input

The first line of the input gives the number of test cases, T (1 ≤ T ≤ 100).

T test cases follow.

Each test case starts with a positive integer M (1 ≤ M ≤ 100) on a line by itself -- the number of troublesome pairs of League members.

The next M lines each contain a pair of names, separated by a single space.

Each member name will consist of only letters and the underscore character "_".

Names are case-sensitive.

No pair will appear more than once in the same test case.

Each pair will contain two distinct League members.

Output

For each test case, output one line containing "Case #x: y", where x is the case number (starting from 1) and y is either "Yes" or "No", depending on whether the League members mentioned in the input can be split into two groups with neither of the groups containing a troublesome pair.

Sample Input

2
1
Dead_Bowie Fake_Thomas_Jefferson
3
Dead_Bowie Fake_Thomas_Jefferson
Fake_Thomas_Jefferson Fury_Leika
Fury_Leika Dead_Bowie

Sample Output

Case #1: Yes
Case #2: No
题意:就是给你M组数据,每组两个字符串,表示两者不能共存,将2*M个人分成两组,使得每组中两两都能共存。
思路:看完题目,稍作思考,发现可以用并查集来解决,用map将字符串映射成1~200之间的数字即可,然后开始并查操作,因为只有两组,所以可以用0 表示与根节点在一边,1表示在根节点的另一边。。
附上代码:

#include <iostream>
#include <stdio.h>
#include <string>
#include <string.h>
#include <map>
using namespace std;
int f[220],c[220],flag;
int find(int x)
//查操作
{
if(f[x]==x)return x;
int t=f[x];
f[x]=find(f[x]);
c[x]=(c[x]+c[t])%2;
return f[x];
}
void make(int a,int b) //并操作
{
int f1=find(a);
int f2=find(b);
if(f2!=f1)
{
f[f2]=f1;
if((c[a]+c[b])%2==0)
c[f2]=1;
}
else
{
if((c[a]+c[b])%2==0)
flag=0;
}
}
void init()
{
flag=1;
for(int i=1;i<=210;i++)
{
f[i]=i;
c[i]=0;
}
}
char s1[10000],s2[10000];
int main()
{
int T,n,test=1;
cin>>T;
while(T--)
{
map<string,int>mp;
mp.clear();
init();
cin>>n;
int cnt=1;
for(int i=0;i<n;i++)
{
scanf("%s%s",s1,s2);
if(!mp[s1])mp[s1]=cnt++;
if(!mp[s2])mp[s2]=cnt++;
make(mp[s1],mp[s2]);
}
if(!flag)
printf("Case #%d: Non",test++);
else
printf("Case #%d: Yesn",test++);
}
return 0;
}

最后

以上就是精明大树为你收集整理的ACdream 1056并查集+map的全部内容,希望文章能够帮你解决ACdream 1056并查集+map所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(69)

评论列表共有 0 条评论

立即
投稿
返回
顶部