Advertisement
Guest User

Untitled

a guest
Mar 30th, 2015
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <queue>
  5. using namespace std;
  6.  
  7. class Graph
  8. {
  9. public:
  10. virtual int getVertexCount() = 0;
  11. virtual vector<int> getNeighbours(int vertex) = 0;
  12. virtual void addEdge(int fromVertex, int toVertex) = 0;
  13. // virtual void newGraph(int vertexCount, bool oriented) = 0;
  14. };
  15.  
  16.  
  17. class ListsGraph : public Graph
  18. {
  19. private:
  20. int vertexCount;
  21. bool oriented;
  22. vector<vector<int> > listsGraph;
  23.  
  24. public:
  25.  
  26. ListsGraph(int vertexCount, bool oriented) : vertexCount(vertexCount), oriented(oriented),
  27. listsGraph(vertexCount){};
  28.  
  29. int getVertexCount(){
  30. return vertexCount;
  31. }
  32.  
  33. void addEdge(int fromVertex, int toVertex){
  34. listsGraph[fromVertex].push_back(toVertex);
  35. if(!oriented)
  36. {
  37. listsGraph[toVertex].push_back(fromVertex);
  38. }
  39. }
  40.  
  41. vector<int> getNeighbours(int vertex){
  42. return listsGraph[vertex];
  43. }
  44. };
  45.  
  46. class Bfs
  47. {
  48. public:
  49. static bool run(Graph &graph)
  50. {
  51. int size = graph.getVertexCount();
  52. vector<int> dv(size, -1);
  53.  
  54. for (int j = 0; j < size; j++)
  55. {
  56. if(dv[j] == -1)
  57. {
  58. dv[j] = 0;
  59.  
  60. queue<int> q;
  61. q.push(j);
  62.  
  63.  
  64. while(!q.empty())
  65. {
  66. int v = q.front();
  67. q.pop();
  68. vector<int> neighbours = graph.getNeighbours(v);
  69. for(int i = 0; i < (int)neighbours.size(); i++)
  70. {
  71. if(dv[neighbours[i]] == -1)
  72. {
  73. dv[neighbours[i]] = 1 - dv[v];
  74. q.push(neighbours[i]);
  75. }
  76. else
  77. {
  78. if(dv[v] == dv[neighbours[i]])
  79. {
  80. return false;
  81. }
  82. }
  83. }
  84. }
  85. }
  86. }
  87. return true;
  88. }
  89. };
  90.  
  91. int main()
  92. {
  93. int k;
  94. cin >> k;
  95. for(int i = 0; i < k; i++)
  96. {
  97. int n, m, v1, v2;;
  98. cin >> n >> m;
  99. ListsGraph graph = ListsGraph(n, false);
  100. for(int i = 0; i < m; i++)
  101. {
  102. cin >> v1 >> v2;
  103. v1--;
  104. v2--;
  105. graph.addEdge(v1, v2);
  106. }
  107. bool f = Bfs::run(graph);
  108. if(f)
  109. {
  110. cout << "YES" << endl;
  111. }
  112. else
  113. {
  114. cout << "NO" << endl;
  115. }
  116. }
  117. return 0;
  118. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement