BZOJ1266 AHOI2006上学路线(最短路+最小割)
求出最短路后找出可能在最短路上的边,显然割完边后我们需要让图中这样的边无法构成1到n的路径,最小割即可,非常板子。
#include<iostream> #include<cstdio> #include<cmath> #include<cstdlib> #include<cstring> #include<algorithm> using namespace std; int read() { int x=0,f=1;char c=getchar(); while (c<'0'||c>'9') {if (c=='-') f=-1;c=getchar();} while (c>='0'&&c<='9') x=(x<<1)+(x<<3)+(c^48),c=getchar(); return x*f; } #define N 510 #define M 250000 #define inf 2000000000 int n,m,p[N],d[N],t=0; bool flag[N]; struct data{int to,nxt,len,cost; }edge[M]; void addedge(int x,int y,int z,int c){t++;edge[t].to=y,edge[t].nxt=p[x],edge[t].len=z,edge[t].cost=c,p[x]=t;} namespace flow { int cur[N],q[N],d[N],ans=0; struct data{int to,nxt,cap,flow; }edge[M]; void addedge(int x,int y,int z) { t++;edge[t].to=y,edge[t].nxt=p[x],edge[t].cap=z,edge[t].flow=0,p[x]=t; t++;edge[t].to=x,edge[t].nxt=p[y],edge[t].cap=0,edge[t].flow=0,p[y]=t; } bool bfs() { memset(d,255,sizeof(d));d[1]=0; int head=0,tail=1;q[1]=1; do { int x=q[++head]; for (int i=p[x];~i;i=edge[i].nxt) if (d[edge[i].to]==-1&&edge[i].flow<edge[i].cap) { d[edge[i].to]=d[x]+1; q[++tail]=edge[i].to; } }while (head<tail); return ~d[n]; } int work(int k,int f) { if (k==n) return f; int used=0; for (int i=cur[k];~i;i=edge[i].nxt) if (d[k]+1==d[edge[i].to]) { int w=work(edge[i].to,min(f-used,edge[i].cap-edge[i].flow)); edge[i].flow+=w,edge[i^1].flow-=w; if (edge[i].flow<edge[i].cap) cur[k]=i; used+=w;if (used==f) return f; } if (used==0) d[k]=-1; return used; } void dinic() { while (bfs()) { memcpy(cur,p,sizeof(p)); ans+=work(1,inf); } cout<<ans; } } int main() { #ifndef ONLINE_JUDGE freopen("bzoj1266.in","r",stdin); freopen("bzoj1266.out","w",stdout); const char LL[]="%I64d\n"; #else const char LL[]="%lld\n"; #endif n=read(),m=read(); for (int i=1;i<=m;i++) { int x=read(),y=read(),z=read(),c=read(); addedge(x,y,z,c);addedge(y,x,z,c); } memset(d,42,sizeof(d));d[1]=0; for (int i=1;i<=n;i++) { int mn=0; for (int j=1;j<=n;j++) if (!flag[j]&&d[j]<d[mn]) mn=j; flag[mn]=1; for (int j=p[mn];j;j=edge[j].nxt) if (d[mn]+edge[j].len<d[edge[j].to]) d[edge[j].to]=d[mn]+edge[j].len; } cout<<d[n]<<endl; t=-1;memset(p,255,sizeof(p)); for (int i=1;i<=m;i++) { if (d[edge[i<<1].to]+edge[i<<1].len==d[edge[i*2-1].to]) flow::addedge(edge[i<<1].to,edge[i*2-1].to,edge[i<<1].cost); if (d[edge[i*2-1].to]+edge[i*2-1].len==d[edge[i<<1].to]) flow::addedge(edge[i*2-1].to,edge[i<<1].to,edge[i<<1].cost); } flow::dinic(); return 0; }