标签:
1 #include<iostream> 2 #include<cstdio> 3 #include<cmath> 4 #include<algorithm> 5 #include<stack> 6 #include<queue> 7 #include<cstring> 8 #define PAU putchar(‘ ‘) 9 #define ENT putchar(‘\n‘) 10 #define MSE(a,b) memset(a,b,sizeof(a)) 11 #define REN(x) for(ted*e=fch[x];e;e=e->nxt) 12 #define TIL(x) for(int i=1;i<=x;i++) 13 using namespace std; 14 const int maxn=2000+10,maxm=20000+10,inf=1e9; 15 struct zkw{ 16 struct ted{int x,y,w,c;ted*nxt,*re;}adj[maxm],*fch[maxn],*ms; 17 int n,S,T,d[maxn],cost,ans;bool inq[maxn],vis[maxn]; 18 void init(int n){this->n=n;ms=adj;MSE(vis,false);MSE(inq,false);return;} 19 void add(int x,int y,int w,int c){ 20 *ms=(ted){x,y,w,c,fch[x],ms+1};fch[x]=ms++; 21 *ms=(ted){y,x,0,-c,fch[y],ms-1};fch[y]=ms++; 22 return; 23 } 24 bool bfs(){ 25 TIL(n)d[i]=inf;queue<int>Q;Q.push(T);d[T]=0; 26 while(!Q.empty()){ 27 int x=Q.front();Q.pop();inq[x]=false;REN(x){ 28 int v=e->y;if(e->re->w&&d[v]>d[x]+e->re->c){ 29 d[v]=d[x]+e->re->c;if(!inq[v])inq[v]=true,Q.push(v); 30 } 31 } 32 }for(ted*e=adj;e!=ms;e++)e->c+=d[e->y]-d[e->x];cost+=d[S];return d[S]!=inf; 33 } 34 int dfs(int x,int aug){ 35 if(x==T||!aug)return(ans+=aug*cost,aug);int flow=0,k;vis[x]=true;REN(x){ 36 int v=e->y;if(e->w&&!e->c&&!vis[v]&&(k=dfs(v,min(aug,e->w)))){ 37 e->w-=k;e->re->w+=k;flow+=k;aug-=k;if(!aug)break; 38 } 39 }return flow; 40 } 41 int mcmf(int S,int T){ 42 this->S=S;this->T=T;while(bfs())do MSE(vis,false);while(dfs(S,inf));return ans; 43 } 44 }sol; 45 inline int read(){ 46 int x=0,sig=1;char ch=getchar(); 47 for(;!isdigit(ch);ch=getchar())if(ch==‘-‘)sig=0; 48 for(;isdigit(ch);ch=getchar())x=10*x+ch-‘0‘; 49 return sig?x:-x; 50 } 51 inline void write(int x){ 52 if(x==0){putchar(‘0‘);return;}if(x<0)putchar(‘-‘),x=-x; 53 int len=0,buf[15];while(x)buf[len++]=x%10,x/=10; 54 for(int i=len-1;i>=0;i--)putchar(buf[i]+‘0‘);return; 55 } 56 int n,m; 57 int main(){ 58 n=read();m=read();sol.init(n);int x,y,w; 59 TIL(m)x=read(),y=read(),w=read(),sol.add(x,y,w,read());write(sol.mcmf(1,n)); 60 return 0; 61 }
标签:
原文地址:http://www.cnblogs.com/chxer/p/4740581.html