【題解】Codeforces EDU Course-2 Lesson-7-1 D. Cutting a graph

【題目敘述】http://codeforces.com/edu/course/2/lesson/7/1/practice/contest/289390/problem/D
【解題想法】用離線把刪邊轉換成加邊

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
 
int n, m, k, p[100005];
vector <pair<string, pair<int, int> > > v;
vector <string> ans;
 
int pa(int x){
    if (x == p[x]) return x;
    return p[x] = pa(p[x]);
}
 
int main() {
    cin >> n >> m >> k;
    for (int i = 1; i <= n; i++){
        p[i] = i;
    }
    for (int i = 0, u, v; i < m; i++){
        cin >> u >> v;
    }
    string s;
    for (int i = 0, u, w; i < k; i++){
        cin >> s >> u >> w;
        v.push_back({s, {u, w}});
    }
    while (v.size()){
        int x = v.back().second.second, y = v.back().second.first;
        x = pa(x);
        y = pa(y);
        if (v.back().first == "cut"){
            p[y] = x;
        }
        else{
            if (x == y) ans.push_back("YES");
            else ans.push_back("NO");
        }
        v.pop_back();
    }
    reverse(ans.begin(), ans.end());
    for (auto i:ans){
        cout << i << "\n";
    }
}
分享本文 Share with friends