(beginer) DFS (二分图判定) UVA 11080 Place the Guards

来源:互联网 发布:程序员帅哥 编辑:程序博客网 时间:2024/05/16 09:26

Problem G

Place the Guards
Input: Standard Input

Output: Standard Output

In the country of Ajabdesh there are some streets and junctions. Each street connects 2 junctions. The king of Ajabdesh wants to place some guards in some junctions so that all the junctions and streets can be guarded by them. A guard in a junction can guard all the junctions and streets adjacent to it. But the guards themselves are not gentle. If a street is guarded by multiple guards then they start fighting. So the king does not want the scenario where a street may be guarded by two guards. Given the information about the streets and junctions of Ajabdesh, help the king to find the minimum number of guards needed to guard all the junctions and 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 of junctions and e is the number of streets. Each of the next e line contains 2 integer f and t denoting that 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 needed to guard all the junctions and streets. Set the value of m as -1 if it is impossible to place the guards without fighting.

 

Sample Input                             Output for Sample Input

2

4 2

0 1

2 3

5 5

0 1

1 2

2 3

0 4

3 4

 

2

-1

 


题意:要为图上面的点安排保镖,一个保镖能看守他所在的点和相邻的点和边,但是同一条边只能被一个保镖看守,问最少需要多少个保镖。

思路:其实一条边的两个节点,一定要有一个放保镖,所以如果可以满足的话,那么肯定能够构成一个二分图。一边是被看守,一边是放了保镖的。所以就转换为判定二分图的问题了。

代码:
#include<iostream>
#include<cstring>
#include<string.h>
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
const int maxn = 200+5;
vector<int> G[maxn];
int color[maxn];
int S[maxn] , c;
int n , m;

void init()
{
for (int i = 0 ; i < n ; ++i) G[i].clear();
memset(color,0,sizeof(color));
}

void input()
{
while (m--)
{
int u , v;
scanf("%d%d",&u,&v);
G[u].push_back(v);
G[v].push_back(u);
}
}

bool bipartite(int u)
{
S[c++] = u;
for (int i = 0 ; i < G[u].size() ; ++i)
{
int v = G[u][i];
if (color[v]==color[u]) return false;
if (!color[v])
{
color[v] = 3-color[u];
if (!bipartite(v)) return false;
}
}
return true;
}

void solve()
{
int ans = 0;
for (int i = 0 ; i < n ; ++i) if (!color[i])
{
color[i] = 1;
int cnt = c = 0;
if (!bipartite(i)) {
printf("-1\n");
return;
} else {
for (int i = 0 ; i < c ; ++i)
cnt += color[S[i]] == 1;
cnt = min(cnt,c-cnt);
if (c==1) cnt = 1;
ans += cnt;
}
}
cout << ans << endl;
}

int main()
{
int T; cin>>T;
while (T--)
{
scanf("%d%d",&n,&m);
init();
input();
solve();
}
}
0 0
原创粉丝点击