思路
建议先看 P1525 [NOIP 2010 提高组] 关押罪犯 .
那么对区间 ,只取编号 的区间,这里直接处理时不用管其余边.
我们想要最小化同一块内部最大边权,与关押罪犯等价做法:边权从大到小依次尝试加入,保留能构成二分图的极大集合;第一条不能加入(产生奇环)的边权就是答案;全都能加则 -1。
code
#include<bits/stdc++.h>
using namespace std;
const int N = 2005; // n<=1000,2*N足够
int fa[2 * N];
struct node {
int x, y, w, id; // id存边原始编号
}a[100005];
int n, m, q;
int find(int u) {
if (fa[u] == u) return u;
return fa[u] = find(fa[u]);
}
void unionn(int x, int y) {
x = find(x), y = find(y);
if (x != y) fa[x] = y;
return ;
}
bool cmp(node q, node h) {
return q.w > h.w; // 从大到小排序,和你原来一致
}
int main () {
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
cin >> n >> m >> q;
for (int i = 1; i <= m; ++i) {
cin >> a[i].x >> a[i].y >> a[i].w;
a[i].id = i; // 记录原始边编号
}
// 全局按权从大到小排序
sort(a + 1, a + 1 + m, cmp);
while(q--) {
int L, R;
cin >> L >> R;
// 初始化扩展域并查集
for (int i = 1; i <= 2 * n; ++i) fa[i] = i;
int ans = -1;
// 遍历所有边,只选用id∈[L,R]的边
for (int i = 1; i <= m; ++i) {
int x = a[i].x, y = a[i].y, w = a[i].w;
int id = a[i].id;
if (id < L || id > R) continue;
if (find(x) == find(y)) {
// 出现奇环,这条边就是答案
ans = w;
break;
}
unionn(x + n, y);
unionn(y + n, x);
}
cout << ans << '\n';
}
return 0;
}