Time Limit: 10000/3000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 243 Accepted Submission(s): 63
#include<cstdio> #include<cstring> #define N 105 #define inf 999999999 #define min(a,b) ((a)<(b)?(a):(b)) int n,m,s,t,num,flow; int low[N],pre[N],adj[N],q[N]; struct edge { int u,v,c,w,next; edge(){} edge(int uu,int vv,int ww,int cc,int n) {u=uu;v=vv;c=cc;w=ww;next=n;} }e[8005]; void insert(int u,int v,int w,int c) { e[num]=edge(u,v,w,c,adj[u]); adj[u]=num++; e[num]=edge(v,u,-w,0,adj[v]); adj[v]=num++; } int spfa() { int i,x,f[N]={0},head=0,tail=0; q[++tail]=s; memset(low,0x3f,sizeof(low)); pre[s]=-1; low[s]=0; while(head!=tail) { x=q[head=(head+1)%N]; f[x]=0; for(i=adj[x];i!=-1;i=e[i].next) if(e[i].c&&low[e[i].v]>low[x]+e[i].w) { pre[e[i].v]=i; low[e[i].v]=low[x]+e[i].w; if(!f[e[i].v]) { f[e[i].v]=1; q[tail=(tail+1)%N]=e[i].v; } } } return low[t]<inf; } int mincost() { int ans=0; while(spfa()) { int v,minflow=inf; for(v=pre[t];v!=-1;v=pre[e[v].u]) minflow=min(minflow,e[v].c); for(v=pre[t];v!=-1;v=pre[e[v].u]) { e[v].c-=minflow; e[v^1].c+=minflow; } ans+=minflow*low[t]; flow+=minflow; } return ans; } int main() { int u,v,a,b,T,ss,tt,c=0; scanf("%d",&T); while(T--) { int i,cost,sum=0,tmp=0,in[105]={0},out[105]={0}; scanf("%d%d%d%d",&n,&m,&ss,&tt); num=flow=0; memset(adj,-1,sizeof(adj)); while(m--) { scanf("%d%d%d%d",&u,&v,&a,&b); if(a<b) { insert(v,u,b-a,1); sum+=a; in[v]++; out[u]++; } else { insert(u,v,a-b,1); sum+=b; } } in[ss]++; out[tt]++; s=0; t=n+1; for(i=1;i<=n;i++) { if(in[i]>out[i]) { insert(s,i,0,in[i]-out[i]); tmp+=in[i]-out[i]; } else insert(i,t,0,out[i]-in[i]); } cost=mincost(); printf("Case %d: ",++c); if(flow==tmp) printf("%d\n",sum+cost); else puts("impossible"); } }