int answer[MAXQ]= {0}; structquerySt { int index; int x, y; int lim;
querySt (int find = 0, int fx = 0, int fy = 0, int flim = 0) : index (find), x (fx), y (fy), lim (flim) {} } ; querySt query[MAXQ];
querySt q1[MAXQ], q2[MAXQ]; int father[MAXN], subsize[MAXN]; pair<int, int> stack[MAXM]; int top = 0; intfind(int x){ return father[x] == x ? x : find (father[x]); } voidmerge(int x, int y){ int fx = find (x), fy = find (y); if (fx == fy) return ; if (subsize[fx] > subsize[fy]) swap (fx, fy); father[fx] = fy, subsize[fy] += subsize[fx]; stack[++ top] = make_pair (fx, fy); } voidsolve(int left, int right, int l, int r){ // if (left > right || l > r) return ; 注意若 l > r 就退出那么有一些点无法加入并查集 top = 0; if (left == right) { // cout << "Test: " << left << ' ' << l << ' ' << r << endl; for (int i = l; i <= r; i ++) answer[query[i].index] = left; merge (edge[left].first, edge[left].second); top = 0; return ; } int mid = (left + right) >> 1; for (int i = left; i <= mid; i ++) { int u = edge[i].first, v = edge[i].second; merge (u, v); } int t1 = 0, t2 = 0; for (int i = l; i <= r; i ++) { int x = query[i].x, y = query[i].y; int lim = query[i].lim; int fx = find (x), fy = find (y); if (fx == fy) { if (subsize[fx] >= lim) q1[++ t1] = query[i]; else q2[++ t2] = query[i]; } else { if (subsize[fx] + subsize[fy] >= lim) q1[++ t1] = query[i]; else q2[++ t2] = query[i]; } } for (int i = 1; i <= t1; i ++) query[l + i - 1] = q1[i]; for (int i = 1; i <= t2; i ++) query[l + t1 + i - 1] = q2[i]; while (top > 0) { int x = stack[top].first, y = stack[top].second; top --; father[x] = x, subsize[y] -= subsize[x]; } solve (left, mid, l, l + t1 - 1), solve (mid + 1, right, l + t1, r); }
intgetnum(){ int num = 0; char ch = getchar ();
while (! isdigit (ch)) ch = getchar (); while (isdigit (ch)) num = (num << 3) + (num << 1) + ch - '0', ch = getchar ();
N = getnum (), M = getnum (); for (int i = 1; i <= M; i ++) { int u = getnum (), v = getnum (); edge[i] = make_pair (u, v); } Q = getnum (); for (int i = 1; i <= Q; i ++) { int x = getnum (), y = getnum (), z = getnum (); query[i] = querySt (i, x, y, z); } for (int i = 1; i <= N; i ++) father[i] = i, subsize[i] = 1; solve (1, M, 1, Q); for (int i = 1; i <= Q; i ++) printf ("%d\n", answer[i]);