739. [网络流24题] 运输问题
★★ 输入文件:tran.in
输出文件:tran.out
简单对比
时间限制:1 s 内存限制:128 MB
«问题描述:
«编程任务:
对于给定的m 个仓库和n 个零售商店间运送货物的费用,计算最优运输方案和最差运
输方案。
«数据输入:
«结果输出:
程序运行结束时,将计算出的最少运输费用和最多运输费用输出到文件tran.out中。
输入文件示例 输出文件示例
tran.in
2 3
220 280
170 120 210
77 39 105
150 186 122
tran.out
69140
对于所有数据:1<=N,M<=100
SOLUTION:
这题上来一看很蒙,费用流一直做得都是求最小(本蒟蒻太弱),这题让求最坏的情况,但是反过来一想其实很简单,先把最优情况求出来,再将所有的容量、花费变为负数,这样求出来的就是负数中的最小值,再乘以-1就成了最多运输费。
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 using namespace std; 5 #define inf 10000007 6 int read() { 7 int s=0,f=1; 8 char ch=getchar(); 9 while(ch>'9'||ch<'0') { 10 if(ch=='-') { 11 f=-1; 12 } 13 ch=getchar(); 14 } 15 while(ch>='0'&&ch<='9') { 16 s=(s<<1)+(s<<3)+(ch^48); 17 ch=getchar(); 18 } 19 return s*f; 20 } 21 int n,S,T,r[202],tot,m; 22 struct node { 23 int to,vv,cost,next; 24 } c[400005]; 25 void add(int x,int y,int z,int q) { 26 c[tot]=(node) { 27 y,z,q,r[x] 28 }; 29 r[x]=tot++; 30 } 31 int queue[100005],head,tail; 32 int dis[202],pre[202],path[202]; 33 bool vis[202]; 34 bool bfs(int s,int t) { 35 head=tail=0; 36 memset(vis,0,sizeof(vis)); 37 memset(pre,-1,sizeof(pre)); 38 memset(dis,30,sizeof(dis)); 39 dis[s]=0; 40 queue[++tail]=s; 41 vis[s]=1; 42 while(head<tail) { 43 int k=queue[++head]; 44 vis[k]=0; 45 for(int i=r[k]; ~i; i=c[i].next) { 46 if(c[i].vv&&dis[c[i].to]>dis[k]+c[i].cost) { 47 dis[c[i].to]=dis[k]+c[i].cost; 48 pre[c[i].to]=k; 49 path[c[i].to]=i; 50 if(!vis[c[i].to]) { 51 vis[c[i].to]=1; 52 queue[++tail]=c[i].to; 53 } 54 } 55 } 56 } 57 if(pre[t]==-1) { 58 return false; 59 } else { 60 return true; 61 } 62 } 63 int dinic(int s,int t) { 64 int ans=0,f=0x7fffffff; 65 while(bfs(s,t)) { 66 for(int i=t; i!=s; i=pre[i]) { 67 if(c[path[i]].vv<f) { 68 f=c[path[i]].vv; 69 } 70 } 71 ans+=dis[t]*f; 72 for(int i=t; i!=s; i=pre[i]) { 73 c[path[i]].vv-=f; 74 c[path[i]^1].vv+=f; 75 } 76 } 77 return ans; 78 } 79 int main() { 80 freopen("tran.in","r",stdin); 81 freopen("tran.out","w",stdout); 82 memset(r,-1,sizeof(r)); 83 m=read(); 84 n=read(); 85 S=0,T=n+m+1; 86 for(int i=1,x; i<=m; i++) { 87 x=read(); 88 //cout<<i<<endl; 89 add(S,i,x,0); 90 add(i,S,0,0); 91 } 92 for(int i=m+1,x; i<=m+n; i++) { 93 //cout<<i<<endl; 94 x=read(); 95 add(i,T,x,0); 96 add(T,i,0,0); 97 } 98 for(int i=1; i<=m; i++) { 99 for(int j=m+1,x; j<=n+m; j++) { 100 //cout<<j<<endl; 101 x=read(); 102 add(i,j,inf,x); 103 add(j,i,0,-x); 104 } 105 } 106 int ans=dinic(S,T); 107 printf("%d\n",ans); 108 for(int i=0; i<tot; i+=2) { 109 c[i].cost*=-1; 110 c[i^1].cost*=-1; 111 c[i].vv+=c[i^1].vv; 112 c[i^1].vv=0; 113 } 114 ans=-dinic(S,T); 115 printf("%d\n",ans); 116 return 0; 117 }