Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

c++ - What is wrong in my code for finding if a graph is Bipartite or not?

I am doing a simple BFS and marks the neighbouring elements for the vertices which comes under the current traversing vertice and if it's again found in the next vertices of the current traversing vertice then it's not a bipartite.

#include <bits/stdc++.h>

using namespace std;

vector<long> g[100000];

void neighbour(long it, vector<bool>& nei)
{
    for (auto itr : g[it])
        nei[itr] = true;
}

bool BFSbipartile(vector<bool>& vis, long v, long ver)
{
    queue<long> q;

    bool flag = true;
    q.push(v);
    vis[v] = true;
    while (!q.empty()) {
        long t = q.front();
        q.pop();
        vector<bool> nei(ver + 1, false);
        for (auto it : g[t]) {
            if (!vis[it]) {
                neighbour(it, nei);
                if (nei[it] == true) {
                    flag = false;
                    break;
                }
                vis[it] = true;
                q.push(it);
            }
            if (!flag)
                return false;
        }
    }
    return true;
}

int main()
{
    long v, e, e1, e2;
    cin >> v >> e;
    for (long i = 0; i < e; i++) {
        cin >> e1 >> e2;
        g[e1].push_back(e2);
        g[e2].push_back(e1);
    }
    vector<bool> vis(v + 1, false);
    bool tru = true;
    for (int i = 1; i <= v; i++) {
        if (!vis[i])
            tru = BFSbipartile(vis, i, v);
        if (!tru) {
            cout << 0 << endl;
            break;
        }
    }
    if (tru)
        cout << 1 << endl;

    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...