Problem G
Place the Guards
Input: Standard Input
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 2="2" begins="begins" case="case" cases.="cases." class="GramE" each="each" indicating="indicating" nbsp="nbsp" number="number" of="of" span="span" test="test" the="the" with="with">integers80>
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
|
Problemsetter: Abdullah-al-Mahmud
Special Thanks: Md. Kamruzzaman
#include<stdio.h>
#include<cstring>
#include<string>
#include<algorithm>
#include<vector>
#define REP(i, b, n) for (int i = b; i < n; i++)
#define rep(i,n) REP(i, 0, n)
#define DBG 0
using namespace std;
int N,E,color[200],cn;
vector<int>egs[200];
bool trav[200];
bool mark(int u,int cr,int &len){
int b;
if(DBG)printf("mark %d %d\n",u,cr);
trav[u]=1,color[u]=cr;
if(cr==1)cn++;
int nc=(cr==1?2:1);
rep(i,egs[u].size()){
b=egs[u][i];
if(color[b]&&color[b]!=nc)return 0; //traverse and wrong color
if(!trav[b])len++,mark(b,nc,len);
}
return 1;
}
void ans(){
int tot=0,len,c;
bool fail=0;
memset(color,0,sizeof(color));
memset(trav,0,sizeof(trav));
rep(i,N){
if(!trav[i]){
cn=0,len=1;
if(mark(i,1,len)){
if(DBG)printf("len cn %d %d\n",len,cn);
c=min(cn,len-cn);
if(c==0)c=1;
tot+=c;
}
else {fail=1;break;}
}
}
if(!fail)printf("%d\n",tot);
else printf("-1\n");
}
int main(){
int n,m,a,b;
scanf("%d",&n);
rep(i,n){
rep(i,200)egs[i].clear();
E=0;
scanf("%d%d",&N,&m);
rep(i,m)scanf("%d%d",&a,&b),egs[a].push_back(b),egs[b].push_back(a),E++;
ans();
}
}
沒有留言:
張貼留言