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;
}