题意
有 N N N个站有 M M M条边连着,其中每条边只能通过 l ∼ r l\sim r l∼r的东西,我们要找出一种办法使得通过的东西最多且字典序最小。
思路
30分暴力搜索。
100分,枚举
l
l
l再二分
r
r
r,用并查集来判断是否可以通过包含这范围内的边走到终点。
代码
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct node{
int x, y, l, r;
}a[3001];
int N, M, ma, anss, ansl;
int father[1001];
int cmp(node x, node y) {
return x.r < y.r;
}
int find(int x) {
return father[x] == x ? x : father[x] = find(father[x]);
}
int check(int l, int r) {//判断
for (int i = 1; i <= N; i++) father[i] = i;
for (int i = M; i >= 1; i--) {
if (a[i].r < r) break;//优化
if (a[i].l <= l && a[i].r >= r) father[find(a[i].y)] = find(a[i].x);
}
return find(1) == find(N);
}
int main() {
scanf("%d %d", &N, &M);
for (int i = 1; i <= M; i++) {
scanf("%d %d %d %d", &a[i].x, &a[i].y, &a[i].l, &a[i].r);
ma = max(ma, a[i].r);
}
sort(a + 1, a + M + 1, cmp);
for (int i = 1; i <= M; i++) {
int l1 = 0, l2 = ma, mid, s = 0;
while (l1 < l2) {//二分r
mid = (l1 + l2 + 1) >> 1;
if (check(a[i].l, mid)) {
l1 = mid;
s = mid - a[i].l + 1;
}
else l2 = mid - 1;
}
if (s > anss || (s == anss && a[i].l < ansl)) anss = s, ansl = a[i].l;
}
printf("%d\n", anss);
for (int i = ansl; i < ansl + anss; i++) printf("%d ", i);
}