LCT 最小生成树
先对边按照a排个序,就像cdq分治那样除去其中一维的影响,而b用LCT动态维护最大值。
当边的两端不连通时直接加边,否则找到两端路径上b的最大值,与当前边比较考虑是否加入并删除原来的边。
但是LCT搞不了边权,可以把一条边变成一个点,然后并把边权赋给这个点(如 x−>y x − > y 变成 x−>z−>y x − > z − > y )。
代码:
#include<cctype>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 50005
#define M 100005
#define F inline
#define V F void
using namespace std;
struct edge{ int x,y,a,b; }ed[M<<2];
struct node{ int to[2],fa,f,p,mx; }t[N<<2];
int n,m,k,tp,h[N<<2],fa[N<<2],stk[N<<2];
F char readc(){
static char buf[100000],*l=buf,*r=buf;
if (l==r) r=(l=buf)+fread(buf,1,100000,stdin);
if (l==r) return EOF; return *l++;
}
F int _read(){
int x=0; char ch=readc();
while (!isdigit(ch)) ch=readc();
while (isdigit(ch)) x=(x<<3)+(x<<1)+(ch^48),ch=readc();
return x;
}
F bool cmp(edge x,edge y){ return x.a<y.a; }
int findfa(int x){ return x==fa[x]?x:fa[x]=findfa(fa[x]); }
#define rt(x) (t[t[x].fa].to[0]!=(x)&&t[t[x].fa].to[1]!=(x))
V pshp(int x){
int l=t[x].to[0],r=t[x].to[1]; t[x].p=x;
if (t[t[l].p].mx>t[t[x].p].mx) t[x].p=t[l].p;
if (t[t[r].p].mx>t[t[x].p].mx) t[x].p=t[r].p;
}
V pshd(int x){
if (!t[x].f) return; int &l=t[x].to[0],&r=t[x].to[1];
t[l].f^=1,t[r].f^=1,t[x].f=0,swap(l,r);
}
V rtt(int x){
int y=t[x].fa,z=t[y].fa,l=(t[y].to[0]==x);
if (!rt(y)) t[z].to[t[z].to[0]!=y]=x;
t[x].fa=z,t[y].fa=x,t[t[x].to[l]].fa=y;
t[y].to[l^1]=t[x].to[l],t[x].to[l]=y;
pshp(y),pshp(x);
}
V splay(int x){
for (int i=stk[tp=1]=x;!rt(i);i=t[i].fa) stk[++tp]=t[i].fa;
while (tp) pshd(stk[tp--]);
for (int y=t[x].fa,z=t[y].fa;!rt(x);rtt(x),y=t[x].fa,z=t[y].fa)
if (!rt(y)) rtt((t[z].to[0]==y^t[y].to[0]==x)?x:y);
}
V ccss(int x){ for (int i=0;x;i=x,x=t[x].fa) splay(x),t[x].to[1]=i,pshp(x); }
V mkrt(int x){ ccss(x),splay(x),t[x].f^=1; }
V lnk(int x,int y){ mkrt(x),t[x].fa=y; }
V sprt(int x,int y){ mkrt(x),ccss(y),splay(y); }
V cut(int x,int y){ sprt(x,y); if (t[y].to[0]==x) t[y].to[0]=t[x].fa=0; }
F int srch(int x,int y){ sprt(x,y); return t[y].p; }
int main(){
n=_read(),m=_read(); int ans=2e9;
for (int i=1;i<=n;i++) fa[i]=i;
for (int i=1,x,y,a,b;i<=m;i++)
x=_read(),y=_read(),a=_read(),b=_read(),ed[i]=(edge){x,y,a,b};
sort(ed+1,ed+m+1,cmp);
for (int i=1,v,x,y,fx,fy;i<=m;i++){
if ((fx=findfa(x=ed[i].x))==(fy=findfa(y=ed[i].y)))
if (t[v=srch(x,y)].mx>ed[i].b) cut(v,ed[v-n].x),cut(v,ed[v-n].y);
else{
if (findfa(1)==findfa(n)) ans=min(ans,ed[i].a+t[srch(1,n)].mx);
continue;
}
else fa[fx]=fy;
t[n+i].mx=ed[i].b,t[n+i].p=n+i,lnk(x,n+i),lnk(y,n+i);
if (findfa(1)==findfa(n)) ans=min(ans,ed[i].a+t[srch(1,n)].mx);
}
if (ans==2e9) puts("-1"); else printf("%d\n",ans);
return 0;
}