BZOJ3669 膜法森林 - LCT

时间:2022-03-02 19:56:53

Solution

非常妙的排序啊。。。

仔细想想好像确实能够找出最优解QUQ

先对第一关键字排序, 在$LCT$ 维护第二关键字的最大值 所在的边。

添边时如果$u, v$ 不连通 就直接加边。  如果连通 并且路径上的最大值 大于 当前边 的 第二关键字, 那么可以换掉。

如果 $1$ 和 $N$ 连通 就 更新答案。

这样就可以保证 在 所有路径上的边 第一关键字 小于等于 当前边 的第一关键字的前提下, 第二关键字的 最大值  最小。

除了这一点不一样, 其他就是模板了。

Code

 #include<cstdio>
#include<cstring>
#include<algorithm>
#define rd read()
using namespace std; const int N = 1e5 + ;
const int inf = ~0U >> ; int n, m;
int ans = inf; struct edge {
int u, v, a, b;
}e[N << ]; int read() {
int X = , p = ; char c = getchar();
for (; c > '' || c < ''; c = getchar())
if (c == '-') p = -;
for (; c >= '' && c <= ''; c = getchar())
X = X * + c - '';
return X * p;
} int cmp(const edge &A, const edge &B) {
return A.a < B.a;
} void cmin(int &A, int B) {
if (A > B)
A = B;
} namespace LCT {
int val[N << ], f[N << ], ch[N << ][], mx[N << ], tun[N << ];
#define lc(x) ch[x][0]
#define rc(x) ch[x][1] int isroot(int x) {
return lc(f[x]) != x && rc(f[x]) != x;
} int get(int x) {
return rc(f[x]) == x;
} void up(int x) {
mx[x] = val[x];
if (e[mx[lc(x)]].b > e[mx[x]].b) mx[x] = mx[lc(x)];
if (e[mx[rc(x)]].b > e[mx[x]].b) mx[x] = mx[rc(x)];
} void rev(int x) {
swap(lc(x), rc(x));
tun[x] ^= ;
} void pushdown(int x) {
if (tun[x]) {
if (lc(x)) rev(lc(x));
if (rc(x)) rev(rc(x));
tun[x] = ;
}
} int st[N << ], tp; void pd(int x) {
while (!isroot(x)) {
st[++tp] = x;
x = f[x];
}
pushdown(x);
while (tp) pushdown(st[tp--]);
} void rotate(int x) {
int old = f[x], oldf = f[old], son = ch[x][get(x) ^ ];
if (!isroot(old)) ch[oldf][get(old)] = x;
ch[x][get(x) ^ ] = old;
ch[old][get(x)] = son;
f[old] = x; f[son] = old; f[x] = oldf;
up(old); up(x);
} void splay(int x) {
pd(x);
for (; !isroot(x); rotate(x))
if (!isroot(f[x]))
rotate(get(f[x]) == get(x) ? f[x] : x);
} void access(int x) {
for (int y = ; x; y = x, x = f[x])
splay(x), ch[x][] = y, up(x);
} void mroot(int x) {
access(x); splay(x); rev(x);
} void split(int x, int y) {
mroot(x); access(y); splay(y);
} int findr(int x) {
access(x); splay(x);
while(lc(x)) pushdown(x), x = lc(x);
return x;
} void link(int x, int y) {
mroot(x); f[x] = y;
} void cut(int x, int y) {
split(x, y);
f[x] = ch[y][] = ;
}
}
using namespace LCT; int main()
{
n = rd; m = rd;
for (int i = ; i <= m; ++i) {
e[i].u = rd; e[i].v = rd;
e[i].a = rd; e[i].b = rd;
}
sort(e + , e + + m, cmp);
for (int i = ; i <= m; ++i)
val[i + n] = i;
for (int i = ; i <= m; ++i) {
int x = e[i].u, y = e[i].v, t;
if (x == y) continue;
mroot(x);
if (findr(y) != x)
link(i + n, x), link(i + n, y);
else if (e[t = mx[y]].b > e[i].b)
cut(t + n, e[t].u), cut(t + n, e[t].v),
link(i + n, x), link(i + n, y);
mroot();
if (findr(n) == )
cmin(ans, e[i].a + e[mx[n]].b);
}
printf("%d\n", ans == inf ? - : ans);
}