UVa 11080 Place the Guards

42 篇文章 0 订阅
9 篇文章 0 订阅

In the country of Ajabdesh there are some streets and junctions.Each street connects 2 junctions. The king of Ajabdeshwants to place some guards in some junctions so that all thejunctions and streets can be guarded by them. A guard ina junction can guard all the junctions and streets adjacentto it. But the guards themselves are not gentle. If a streetis guarded by multiple guards then they start fighting. Sothe king does not want the scenario where a street may beguarded by two guards. Given the information about thestreets and junctions of Ajabdesh, help the king to find theminimum number of guards needed to guard all the junctionsand streets of his country.

Input

The first line of the input contains a single integer T (T < 80) indicating the number of test cases.Each test case begins with 2 integers v (1 ≤ v ≤ 200) and e (0 ≤ e ≤ 10000.). v is the number ofjunctions and e is the number of streets. Each of the next e line contains 2 integer f and t denotingthat there is a street between f and t. All the junctions are numbered from 0 to v − 1.

Output

For each test case output in a single line an integer m denoting the minimum number of guards neededto guard all the junctions and streets. Set the value of m as ‘-1’ if it is impossible to place the guardswithout fighting.

Sample Input

2

4 2

0 1

2 3

5 5

0 1

1 2

2 3

0 4

3 4

Sample Output

2

-1

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

二分图染色~

洛谷 P1330 封锁阳光大学很像,详见http://blog.csdn.net/senyelicone/article/details/51919452~

但是这道题有几个坑点:

1.点是从0开始标号的;

2.只有一个点的时候这个单个点要有人看守;

3.图不一定联通.

然后就直接套模板即可,每次判断该点是否遍历过~


#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;

int t,n,m,x,y,cnt,cnt1,cnt2,mark,ans,fi[201],w[20001],ne[20001];
bool b[201],col[201];

void add(int u,int v)
{
	w[++cnt]=v;ne[cnt]=fi[u];fi[u]=cnt;
}

void findd(int u,int v)
{
	b[u]=1;col[u]=v^1;
	if(!v) cnt1++;
	else cnt2++;
	for(int i=fi[u];i!=-1;i=ne[i])
	{
		if(!b[w[i]]) findd(w[i],v^1);
		else if(col[w[i]]==v^1)
		{
			mark=1;return;
		}
	} 
}

int main()
{
	scanf("%d",&t);
	while(t--)
	{
		cnt=mark=ans=0;
		memset(fi,-1,sizeof(fi));
		memset(b,0,sizeof(b));
		memset(col,0,sizeof(col));
		scanf("%d%d",&n,&m);
		for(int i=1;i<=m;i++)
		{
			scanf("%d%d",&x,&y);add(x,y);add(y,x);
		}
		if(n==1)
		{
			printf("1\n");continue;
		}
		for(int i=0;i<n;i++)
		  if(!b[i])
		  {
		  	cnt1=cnt2=0;findd(i,0);
		  	if(!mark)
			{
				if(!cnt1 || !cnt2) ans++;
			  	else ans+=min(cnt1,cnt2);
			}
		  	else break;
		  }
		if(mark)
		{
			printf("-1\n");continue;
		}
		printf("%d\n",ans);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值