Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <algorithm>
- #include <queue>
- using namespace std;
- class Graph
- {
- public:
- virtual int getVertexCount() = 0;
- virtual vector<int> getNeighbours(int vertex) = 0;
- virtual void addEdge(int fromVertex, int toVertex) = 0;
- // virtual void newGraph(int vertexCount, bool oriented) = 0;
- };
- class ListsGraph : public Graph
- {
- private:
- int vertexCount;
- bool oriented;
- vector<vector<int> > listsGraph;
- public:
- ListsGraph(int vertexCount, bool oriented) : vertexCount(vertexCount), oriented(oriented),
- listsGraph(vertexCount){};
- int getVertexCount(){
- return vertexCount;
- }
- void addEdge(int fromVertex, int toVertex){
- listsGraph[fromVertex].push_back(toVertex);
- if(!oriented)
- {
- listsGraph[toVertex].push_back(fromVertex);
- }
- }
- vector<int> getNeighbours(int vertex){
- return listsGraph[vertex];
- }
- };
- class Bfs
- {
- public:
- static bool run(Graph &graph)
- {
- int size = graph.getVertexCount();
- vector<int> dv(size, -1);
- for (int j = 0; j < size; j++)
- {
- if(dv[j] == -1)
- {
- dv[j] = 0;
- queue<int> q;
- q.push(j);
- while(!q.empty())
- {
- int v = q.front();
- q.pop();
- vector<int> neighbours = graph.getNeighbours(v);
- for(int i = 0; i < (int)neighbours.size(); i++)
- {
- if(dv[neighbours[i]] == -1)
- {
- dv[neighbours[i]] = 1 - dv[v];
- q.push(neighbours[i]);
- }
- else
- {
- if(dv[v] == dv[neighbours[i]])
- {
- return false;
- }
- }
- }
- }
- }
- }
- return true;
- }
- };
- int main()
- {
- int k;
- cin >> k;
- for(int i = 0; i < k; i++)
- {
- int n, m, v1, v2;;
- cin >> n >> m;
- ListsGraph graph = ListsGraph(n, false);
- for(int i = 0; i < m; i++)
- {
- cin >> v1 >> v2;
- v1--;
- v2--;
- graph.addEdge(v1, v2);
- }
- bool f = Bfs::run(graph);
- if(f)
- {
- cout << "YES" << endl;
- }
- else
- {
- cout << "NO" << endl;
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement