您的位置:首页 > 其它

Lightoj1009——Back to Underworld(DFS)

2016-09-10 11:08 330 查看
The Vampires and Lykans are fighting each other to death. The war has become so fierce that, none knows who will win. The humans want to know who will survive finally. But humans are afraid of going to the battlefield.

So, they made a plan. They collected the information from the newspapers of Vampires and Lykans. They found the information about all the dual fights. Dual fight means a fight between a Lykan and a Vampire. They know the name of the dual fighters, but don’t know which one of them is a Vampire or a Lykan.

So, the humans listed all the rivals. They want to find the maximum possible number of Vampires or Lykans.

Input

Input starts with an integer T (≤ 10), denoting the number of test cases.

Each case contains an integer n (1 ≤ n ≤ 105), denoting the number of dual fights. Each of the next n lines will contain two different integers u v (1 ≤ u, v ≤ 20000) denoting there was a fight between u and v. No rival will be reported more than once.

Output

For each case, print the case number and the maximum possible members of any race.

Sample Input

2

2

1 2

2 3

3

1 2

2 3

4 2

Output for Sample Input

Case 1: 2

Case 2: 3

两个国家打仗,给出一些两方交战的数据,求两个国家可能的最大军队数,比如样例2:1、3、4就可能是某个国家最大的军队数,所以按照dfs遍历图,每隔一个点标记一个军队,因为敌人的敌人就是自己人。这个图可能不是连通图,所以需要全部遍历,把每个连通块的最大军队加起来

#include <iostream>
#include <cstring>
#include <string>
#include <vector>
#include <queue>
#include <cstdio>
#include <set>
#include <cmath>
#include <algorithm>
#define INF 0x3f3f3f3f
#define MAXN 200005
#define Mod 10001
using namespace std;
int n,m,use[MAXN],vis[MAXN],sum,sum1;
vector<int> mp[MAXN];
void dfs(int x,bool flag)
{
sum++;
if(flag)
sum1++;
vis[x]=1;
for(int i=0;i<mp[x].size();++i)
{
int y=mp[x][i];
if(!vis[y])
{
vis[y]=1;
dfs(y,!flag);
}
}
}
int main()
{
int t,cnt=1;
scanf("%d",&t);
while(t--)
{
scanf("%d",&m);
int u,v;
memset(use,0,sizeof(use));
memset(vis,0,sizeof(vis));
for(int i=0;i<MAXN;++i)
mp[i].clear();
for(int i=0;i<m;++i)
{
scanf("%d%d",&u,&v);
use[u]=use[v]=1;
mp[v].push_back(u);
mp[u].push_back(v);
n=max(n,max(u,v));
}
int ans=0;
for(int i=1;i<=n;++i)
{
if(!use[i])
continue;
if(vis[i])
continue;
sum=sum1=0;
dfs(i,0);
ans+=max(sum1,sum-sum1);
}
printf("Case %d: %d\n",cnt++,ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: