Advertisement
hieudoan

UVa 11080 Place the Guards

Aug 9th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.60 KB | None | 0 0
  1. //11080 Place the Gurards
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4. typedef vector<int> vi;
  5. const int INF=1e7;
  6.  
  7. int T,v,e;
  8. vector<vi> adjList;
  9. vi color;
  10. int BiGcheck(int source, int firstColor){
  11.     queue<int> q;
  12.     q.push(source); //push vào cái giao lộ 0
  13.     color[source]=firstColor;  //1: has guard, 0: no guard
  14.     bool isBipartite=true;
  15.     int cnt=firstColor;
  16.     while(!q.empty()&&isBipartite){
  17.         int u=q.front();
  18.         q.pop();
  19.         for(int i=0;i<adjList[u].size();i++){
  20.             int v=adjList[u][i];
  21.             if(color[v]==INF){
  22.                 color[v]=1-color[u];
  23.                 cnt+=color[v];
  24.                 q.push(v);
  25.             }
  26.             else
  27.                 if(color[v]==color[u]){
  28.                     isBipartite=false;
  29.                     break;
  30.                 }
  31.         }
  32.     }
  33.     if(!isBipartite) return -1;
  34.     if(cnt==0) cnt=1; //1 ngã tư thì có ít nhất 1 guard đứng
  35.     return cnt;
  36. }
  37.  
  38. int main()
  39. {
  40.     scanf("%d",&T);
  41.     while(T--){
  42.         scanf("%d%d",&v,&e);
  43.         adjList.assign(202,vi(0));
  44.         int dau, cuoi;
  45.         while(e--){
  46.             scanf("%d%d",&dau,&cuoi);
  47.             adjList[dau].push_back(cuoi);
  48.             adjList[cuoi].push_back(dau);
  49.         }
  50.    
  51.         int cnt=0;
  52.         color.assign(202,INF);
  53.         vi tmp;
  54.         int x,y;
  55.         for(int i=0;i<v;i++){
  56.             if(color[i]==INF) {
  57.                 tmp=color;
  58.                 x=BiGcheck(i,0);  //cac sub-graph doc lap
  59.                 color=tmp;
  60.                 y=BiGcheck(i,1);  //du x hay y thi sub-graph vẫn chưa all !=iNF
  61.                 if(x==-1 && y==-1) {
  62.                     cnt=-1;
  63.                     break;
  64.                 }
  65.                 else {
  66.                     if(x==-1) cnt+=y;
  67.                     else if(y==-1) cnt+=x;
  68.                     else { //1 ngã tu mà ko ai đứng là ko đưọc
  69.                         cnt+=min(x,y);
  70.                     }
  71.                 }
  72.             }
  73.  
  74.         }
  75.         if(cnt==-1) printf("-1\n");
  76.         else printf("%d\n",cnt);
  77.     }
  78.     return 0;
  79. }
  80. //hieudoanitus
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement