【題解】Codeforces EDU Course-2 Lesson-7-2 J. First Non-Bipartite Edge

【題目敘述】http://codeforces.com/edu/course/2/lesson/7/2/practice/contest/289391/problem/J
【解題想法】啟發式合併

#include <iostream>
#include <vector>
using namespace std;
 
int n, m, p[300005], c[300005];
vector <int> v[300005];
 
int f(int x){
    if (x == p[x]) return x;
    return p[x] = f(p[x]);
}
 
int main() {
    cin >> n >> m;
    for (int i = 1; i <= n; i++){
        p[i] = i;
        v[i].push_back(i);
    }
    for (int i = 1, a, b; i <= m; i++){
        cin >> a >> b;
        if (f(a) == f(b)){
            if (c[a] == c[b]){
                cout << i << "\n";
                exit(0);
            }
        }
        else{
            if (c[a] == c[b]){
                a = f(a);
                b = f(b);
                if (v[a].size() < v[b].size()) swap(a, b);
                p[b] = a;
                while (v[b].size()){
                    c[v[b].back()] ^= 1;
                    v[a].push_back(v[b].back());
                    v[b].pop_back();
                }
            }
            else{
                a = f(a);
                b = f(b);
                if (v[a].size() < v[b].size()) swap(a, b);
                p[b] = a;
                while (v[b].size()){
                    v[a].push_back(v[b].back());
                    v[b].pop_back();
                }
            }
        }
    }
    cout << -1 << "\n";
}
分享本文 Share with friends