- 运输问题4
★★★ 输入文件:maxflowd.in 输出文件:maxflowd.out 简单对比
时间限制:1 s 内存限制:128 MB
【问题描述】
一个工厂每天生产若干商品,需运输到销售部门进行销售。从产地到销地要经过某些城镇,有不同的路线可以行走,每条两城镇间的公路都有一定的流量限制。公路设有收费站,每通过一辆车,要交纳过路费。请你计算,在不考虑其它车辆使用公路的前提下,如何使产地运输到销地的商品最多,并使费用最少。
【输入格式】
输入文件有若干行
第一行,一个整数n,表示共有n个城市(2<=n<=100),产地是1号城市,销地是n号城市
第二行,一个整数,表示起点城市
第三行,一个整数,表示终点城市
下面有n行,每行有2*n个数字。第p行第2*q-1,2*q列的数字表示城镇p与城镇q之间有无公路连接。数字为0表示无,大于0表示有公路,且这两个数字分别表示该公路流量和每车费用。
【输出格式】
输出文件有一行
第一行,1个整数n,表示最小费用为n。
【输入输出样例】
输入文件名: maxflowd.in
6
1
6
0 0 1 3 5 10 0 0 0 0 0 0
0 0 0 0 0 0 5 7 0 0 0 0
0 0 0 0 0 0 0 0 2 8 0 0
0 0 0 0 1 3 0 0 0 0 3 5
0 0 2 4 0 0 0 0 0 0 2 6
0 0 0 0 0 0 0 0 0 0 0 0
输出文件名:maxflowd.out
63
太裸了…
#include<cstdio>
#include<cstring>
#include<queue>
#include<cstdlib>
#include<cmath>
using namespace std;
const int maxn=102;
const int inf=0x7fffffff/3;
struct edge{
int u,next,w,cost,v;
}G[maxn*10];
int dist[maxn];// 从起点s到点u的路径长为d
int vis[maxn];// 点u是否在队列中
int pre[maxn*100],h[maxn*100];
int tot=1,n,s,t,ans;
int path[maxn*100];
void add(int a,int b,int x,int y){
G[++tot].v=b; G[tot].u=a;
G[tot].w=x; G[tot].cost=y;
G[tot].next=h[a]; h[a]=tot;
}
bool spfa(int s,int t){
int u,v;
queue<int>q;
//memset(pre,-1,sizeof(pre));
for(int i=0;i<=n+1;i++){
pre[i]=0;
vis[i]=0;
dist[i]=inf;
}
vis[s]=1;
dist[s]=0;
q.push(s);
while(!q.empty()){
u=q.front();
q.pop();
vis[u]=0;
for(int i=h[u];i;i=G[i].next){
if(G[i].w>0){
v=G[i].v;
if(dist[v]>dist[u]+G[i].cost){
dist[v]=dist[u]+G[i].cost;
pre[v]=u;
path[v]=i;
if(!vis[v]){
vis[v]=true;
q.push(v);
}
}
}
}
}
return dist[t]!=inf;
}
int smallest_cost_flow(){
int ans=0,flow;
int flow_sum=0;
while(spfa(s,t)){
flow=inf;
for(int i=t;i!=s;i=pre[i]){
if(G[path[i]].w<flow)
flow=G[path[i]].w;
}
for(int i=t;i!=s;i=pre[i]){
G[path[i]].w-=flow;
G[path[i]^1].w+=flow;
}
ans+=flow*dist[t];
flow_sum+=flow;
}
return ans;
}
int main()
{
freopen("maxflowd.in","r",stdin);
freopen("maxflowd.out","w",stdout);
scanf("%d%d%d",&n,&s,&t);
int a,b;
for (int i=1;i<=n;++i)
for (int j=1;j<=n;++j){
scanf("%d%d",&a,&b);
if (a!=0&&b!=0){
add(i,j,a,b);
add(j,i,0,-b);
}
}
printf("%d",smallest_cost_flow());
//system("pause");
return 0;
}