Advertisement
urmisaha

Samsung-Graph Coloring

Nov 5th, 2019
339
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.31 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. // Given an undirected connected graph. Color the vertices of the graph with two colors, such that adjacent vertices have different colors. Return the number of vertices colored with 0. If coloring is not possible, return -1.
  6. // Input:
  7. // 8 8
  8. // 1 4
  9. // 4 0
  10. // 4 3
  11. // 1 2
  12. // 2 3
  13. // 2 5
  14. // 7 6
  15. // 5 7
  16.  
  17. // Output:
  18. // 5
  19.  
  20. int n, m, x, y, l, f, c;
  21. int g[10][10];
  22. int color[10];
  23.  
  24. int bfs(){
  25.     for(int i=0; i<n; ++i)
  26.         color[i] = -1;
  27.     int q[100];
  28.     for(int k=0; k<n; ++k){
  29.         f = 0;
  30.         l = 0;
  31.         if(color[k] == -1){
  32.             q[l++] = k;
  33.             color[k] = 0;
  34.         }
  35.         while(f < l){
  36.             x = q[f++];
  37.             c = color[x];
  38.             for(int i=0; i<n; ++i){
  39.                 if(g[x][i]){
  40.                     if(color[i] == -1){
  41.                         color[i] = !c;
  42.                         q[l++] = i;
  43.                     }
  44.                     else if(color[i] == c)
  45.                         return -1;
  46.                 }
  47.             }
  48.         }
  49.     }
  50.     int sum = 0;
  51.     for(int i=0; i<n; ++i)
  52.         if(!color[i])
  53.             sum += 1;
  54.     return sum;
  55. }
  56.  
  57. int main() {
  58.     cin>>n>>m;
  59.     for(int i=0; i<m; ++i){
  60.         cin>>x>>y;
  61.         g[x][y] = 1;
  62.         g[y][x] = 1;
  63.     }
  64.     cout<<bfs();
  65.     return 0;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement