Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <queue>
- using namespace std;
- class Graph {
- private:
- vector<vector<int> > adj;
- vector<int> color;
- public:
- Graph(int n) {
- adj.resize(n);
- color.resize(n, -1);
- }
- void add_edge(int u, int v) {
- adj[u].push_back(v);
- adj[v].push_back(u);
- }
- bool is_bipartite() {
- int n = adj.size();
- for (int i = 0; i < n; ++i) {
- if (color[i] == -1) {
- if (!bfs_check(i)) {
- return false;
- }
- }
- }
- return true;
- }
- bool bfs_check(int start) {
- queue<int> q;
- q.push(start);
- color[start] = 0;
- while (!q.empty()) {
- int u = q.front();
- q.pop();
- for (size_t i = 0; i < adj[u].size(); ++i) {
- int v = adj[u][i];
- if (color[v] == -1) {
- color[v] = 1 - color[u];
- q.push(v);
- } else if (color[v] == color[u]) {
- // Если соседняя вершина имеет тот же цвет, граф не двудольный
- return false;
- }
- }
- }
- return true;
- }
- };
- int main() {
- int N, M;
- cin >> N >> M;
- Graph graph(N);
- for (int i = 0; i < M; ++i) {
- int u, v;
- cin >> u >> v;
- u--;
- v--;
- graph.add_edge(u, v);
- }
- if (graph.is_bipartite()) {
- cout << "YES" << endl;
- } else {
- cout << "NO" << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement