-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGERALD07.cpp
131 lines (113 loc) · 2.56 KB
/
GERALD07.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#include <bits/stdc++.h>
using namespace std;
#define all(foo) foo.begin(), foo.end()
#define sc(a) scanf("%d", &a)
#define sc2(a,b) scanf("%d%d", &a, &b)
#define sc3(a,b,c) scanf("%d%d%d", &a, &b, &c)
#define pri(x) printf("%d\n", x)
#define db(x) cerr << #x << " == " << x << endl
#define dbs(x) cerr << x << endl
#define x first
#define y second
typedef long long ll;
typedef pair<int, int> ii;
struct dsu {
vector<int> hist, par, sz;
vector<ii> changes;
int n;
dsu (int n) : n(n) {
hist.assign(n, 1e9);
par.resize(n);
iota(par.begin(), par.end(), 0);
sz.assign(n, 1);
}
int root (int x, int t) {
if(hist[x] > t) return x;
return root(par[x], t);
}
void join (int a, int b, int t) {
a = root(a, t);
b = root(b, t);
if (a == b) { changes.emplace_back(-1, -1); return; }
if (sz[a] > sz[b]) swap(a, b);
par[a] = b;
sz[b] += sz[a];
hist[a] = t;
changes.emplace_back(a, b);
n--;
}
bool same (int a, int b, int t) {
return root(a, t) == root(b, t);
}
void undo () {
int a, b;
tie(a, b) = changes.back();
changes.pop_back();
if (a == -1) return;
sz[b] -= sz[a];
par[a] = a;
hist[a] = 1e9;
n++;
}
int when (int a, int b) {
while (1) {
if (hist[a] > hist[b]) swap(a, b);
if (par[a] == b) return hist[a];
if (hist[a] == 1e9) return 1e9;
a = par[a];
}
}
};
struct Q{
int l, r, id;
Q () {}
Q (int l, int r, int id) : l(l), r(r), id(id) {}
};
vector<Q> block[700];
const int mx = 212345, magic = 300;
int ans[mx];
ii e[mx];
void solve (int n, int m, vector<Q> &q) {
if (q.empty()) return;
dsu a(n);
sort(all(q), [&] (const Q &a, const Q &b) {
return a.r < b.r;
});
int maxl = ((q[0].l/magic)+1)*magic;
int t = 0;
for (int i = 0, l = maxl; i < q.size(); i++) {
while (l < m && l <= q[i].r) {
a.join(e[l].x, e[l].y, t++), l++;
}
for (int j = q[i].l; j <= min(q[i].r, maxl-1); j++) {
a.join(e[j].x, e[j].y, t++);
}
ans[q[i].id] = a.n;
for (int j = q[i].l; j <= min(q[i].r, maxl-1); j++) a.undo(), t--;
}
}
int main () {
int n, m, q;
int t;
sc(t);
while (t--) {
sc3(n, m, q);
for (int i = 0; i < m; i++) {
sc2(e[i].x, e[i].y);
e[i].x--, e[i].y--;
}
for (int i = 0; i < q; i++) {
int x, y;
sc2(x, y);
x--, y--;
block[x/magic].emplace_back(Q(x, y, i));
}
for (int i = 0; i <= m/magic; i++) {
solve(n, m, block[i]);
block[i].clear();
}
for (int i = 0; i < q; i++) {
pri(ans[i]);
}
}
}