Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Слава Україні, Героям слава
- #include <bits/stdc++.h>
- using namespace std;
- const int N = 2e5 + 7;
- int par[N], sz[N];
- stack<tuple<int, int, int, int>> st;
- int find(int a) {
- return a == par[a] ? a : find(par[a]);
- }
- bool unite(int a, int b) {
- if((a = find(a)) == (b = find(b))) {
- return false;
- }
- if(sz[b] > sz[a]) {
- swap(a, b);
- }
- st.push({a, sz[a], b, par[b]});
- sz[a] += sz[b];
- par[b] = a;
- return true;
- }
- void roll_back() {
- auto [a, b, c, d] = st.top(); st.pop();
- par[c] = d;
- sz[a] = b;
- }
- int n, m, k;
- vector<pair<int, int>> edges, q;
- vector<int> ans;
- void bs(int l, int r, vector<int> &cand) {
- if(l + 1 == r or cand.empty()) {
- for(auto e : cand) {
- ans[e] = l + 1;
- }
- return;
- }
- int mid = (l + r) >> 1, cnt = 0;
- for(int i = l; i < mid; i++) {
- if(unite(edges[i].first, edges[i].second)) {
- cnt++;
- }
- }
- vector<int> pode, npode;
- for(auto e : cand) {
- if(find(q[e].first) == find(q[e].second)) {
- pode.push_back(e);
- } else {
- npode.push_back(e);
- }
- }
- for(int i = 0; i < cnt; i++) {
- roll_back();
- }
- bs(l, mid, pode);
- vector<int>().swap(pode);
- cnt = 0;
- for(int i = l; i < mid; i++) {
- if(unite(edges[i].first, edges[i].second)) {
- cnt++;
- }
- }
- bs(mid, r, npode);
- vector<int>().swap(npode);
- for(int i = 0; i < cnt; i++) {
- roll_back();
- }
- }
- int main() {
- ios_base::sync_with_stdio(false);
- cin.tie(nullptr);
- for(int i = 0; i < N; i++) {
- par[i] = i;
- sz[i] = 1;
- }
- cin >> n >> m >> k;
- edges.resize(m);
- q.resize(k);
- ans.resize(k);
- for(int i = 0; i < m; i++) {
- cin >> edges[i].first >> edges[i].second;
- }
- for(int i = 0; i < k; i++) {
- cin >> q[i].first >> q[i].second;
- }
- vector<int> cand(k);
- iota(cand.begin(), cand.end(), 0);
- bs(0, m + 1, cand);
- for(int i = 0; i < k; i++) {
- if(q[i].first == q[i].second) {
- ans[i] = 0;
- }
- cout << (ans[i] == m + 1 ? -1 : ans[i]) << "\n";
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement