BZOJ 1570 JSOI2008 Blue Mary的旅行 网络流

来源:互联网 发布:常州淘宝运营 编辑:程序博客网 时间:2024/05/23 11:47

题目大意:给定一张有向图,每条边每天最多经过有限次,一个人每天只能经过一条边,T个人从1号点出发,问多少天之后能到达n点

将图分层,每一天分作一层,每一层的点向下一层连边

从源点向第0层的1号点连边

每层的n向T连INF的边

从1开始枚举天数,每多一天就多建一层然后跑最大流,如果当前T个人已经能到达点n则输出答案

由于1~n的路径长度不会超过n,因此T个人排队走这条路径总天数不会超过T+n

故只需要建n+T层即可出解 点数O(n^2+nT) 边数O(mn+mT) 都不是很大 可以跑出来

#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>#define M 5010#define S 0#define T (M-1)#define INF 0x3f3f3f3fusing namespace std;struct edge{int x,y,z;}edges[M];int n,m,t;namespace Max_Flow{struct abcd{int to,f,next;}table[1001001];int head[M],tot=1;int dpt[M];void Add(int x,int y,int z){table[++tot].to=y;table[tot].f=z;table[tot].next=head[x];head[x]=tot;}void Link(int x,int y,int z){Add(x,y,z);Add(y,x,0);}bool BFS(){static int q[M];int i,r=0,h=0;memset(dpt,-1,sizeof dpt);dpt[S]=1;q[++r]=S;while(r!=h){int x=q[++h];for(i=head[x];i;i=table[i].next)if(table[i].f&&!~dpt[table[i].to]){dpt[table[i].to]=dpt[x]+1;q[++r]=table[i].to;if(table[i].to==T)return true;}}return false;}int Dinic(int x,int flow){int i,left=flow;if(x==T) return flow;for(i=head[x];i&&left;i=table[i].next)if(table[i].f&&dpt[table[i].to]==dpt[x]+1){int temp=Dinic(table[i].to,min(left,table[i].f) );left-=temp;table[i].f-=temp;table[i^1].f+=temp;}if(left) dpt[x]=-1;return flow-left;}}int main(){using namespace Max_Flow;int i,j,x,y,z;cin>>n>>m>>t;for(i=1;i<=m;i++){scanf("%d%d%d",&x,&y,&z);edges[i].x=x;edges[i].y=y;edges[i].z=z;}int temp=0;Link(S,1,t);for(i=1;i<=n+t;i++){for(j=1;j<=m;j++)Link(i*n-n+edges[j].x,i*n+edges[j].y,edges[j].z);for(j=1;j<=n;j++)Link(i*n-n+j,i*n+j,INF);Link(i*n+n,T,INF);while( BFS() )temp+=Dinic(S,INF);if(temp==t)return cout<<i<<endl,0;}return 0;}//第i天的点x:i*n+x


0 0