正解是LCT动态维护MST,然而SPFA水过233
SPFA真乃骗分神器233
AC code:
#include <cstdio>
#include <algorithm>
using namespace std;
const int N=500010;
const int M=1000010;
const int K=10000010;
const int INF=1<<28;
int n,m,cnt,cl,pt=1,he,ta,ans=INF;
int head[N],minb[N],lim[K],Q[K];
bool inq[N];
struct Edge{
int v,a,b,next;
Edge() {}
Edge(int v,int a,int b,int next):v(v),a(a),b(b),next(next) {}
}E[M],EE[M];
bool cmp(Edge x,Edge y){
return x.a<y.a;
}
void addedge(int u,int v,int a,int b){
E[++cnt]=Edge(v,a,b,head[u]);
E[++cnt]=Edge(u,a,b,head[v]);
EE[cnt-1]=Edge(v,a,b,head[u]);
EE[cnt]=Edge(u,a,b,head[v]);
head[u]=cnt-1;head[v]=cnt;
}
void read(){
scanf("%d%d",&n,&m);
for(int i=1;i<=m;i++){
int u,v,a,b;
scanf("%d%d%d%d",&u,&v,&a,&b);
addedge(u,v,a,b);
lim[i]=a;
}
}
void SPFA(){
while(he!=ta+1){
int x=Q[he++];
inq[x]=0;
for(int i=head[x];i;i=E[i].next){
if(E[i].a>lim[cl]||minb[E[i].v]<=max(minb[x],E[i].b)) continue;
minb[E[i].v]=max(minb[x],E[i].b);
if(!inq[E[i].v]){
Q[++ta]=E[i].v;
inq[E[i].v]=1;
}
}
}
ans=min(ans,lim[cl]+minb[n]);
}
void work(){
sort(lim+1,lim+m+1);
sort(EE+1,EE+cnt+1,cmp);
he=ta=0;
for(int i=2;i<=n;i++) minb[i]=INF;
for(cl=1;cl<=m;cl++){
if(lim[cl-1]==lim[cl]) continue;
while(EE[pt].a==lim[cl]&&pt<=cnt){Q[++ta]=EE[pt].v;pt++;}
SPFA();
}
if(ans==INF) printf("-1\n");
else printf("%d\n",ans);
}
int main(){
read();
work();
return 0;
}