Advertisement
PlanttPastes

ИИ - Алгоритми 2021 задачи за решавање: Двобојност

Oct 19th, 2021
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.96 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. enum vertex_colour // the colour
  4. {
  5.     UNDEFINED, // non-visited
  6.     RED,
  7.     BLACK
  8. };
  9. struct vertex // a vertex point
  10. {
  11.     vertex_colour colour;
  12.     vector <int> edges_connected;
  13.     vertex()
  14.     {
  15.         colour = UNDEFINED;
  16.         return;
  17.     }
  18. };
  19. vertex_colour opposite(vertex_colour c)
  20. {
  21.     switch (c)
  22.     {
  23.     case RED:
  24.         return BLACK;
  25.     case BLACK:
  26.         return RED;
  27.     case UNDEFINED:
  28.         return UNDEFINED;
  29.     default:
  30.         return UNDEFINED;
  31.     }
  32. }
  33. int main()
  34. {
  35.     int vertices_count, edges; // size of vertices array
  36.     cin >> vertices_count >> edges;
  37.     vector <vertex> vertices(vertices_count); // vertices
  38.     for (int i = 0; i < edges; i++) // input edges
  39.     {
  40.         int a, b;
  41.         cin >> a >> b;
  42.         vertices[a].edges_connected.push_back(b);
  43.         vertices[b].edges_connected.push_back(a);
  44.     }
  45.     queue <int> bfs_queue; // BFS queue
  46.     bfs_queue.push(0); // add vertex 0 to BFS queue
  47.     vertices[0].colour = RED;
  48.     while (!bfs_queue.empty()) // BFS
  49.     {
  50.         int vertex_index = bfs_queue.front(); // get check index for vertex
  51.         bfs_queue.pop();
  52.         for (int i = 0; i < vertices[vertex_index].edges_connected.size(); i++) // check all edges connecting to vertex
  53.         {
  54.             if (vertices[vertices[vertex_index].edges_connected[i]].colour == vertices[vertex_index].colour)
  55.             {
  56.                 cout << "NO"; // two neighbour vertices have same colour
  57.                 return 0;
  58.             }
  59.             if (vertices[vertices[vertex_index].edges_connected[i]].colour == UNDEFINED)
  60.             {
  61.                 vertices[vertices[vertex_index].edges_connected[i]].colour = opposite(vertices[vertex_index].colour);
  62.                 bfs_queue.push(vertices[vertex_index].edges_connected[i]); // colour with opposite colour
  63.             }
  64.         }
  65.     }
  66.     cout << "YES"; // all are coloured
  67.     return 0;
  68. }
  69.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement