Description
Input
There will be at most 200 test cases. Each case begins with two integers n, m (1<=n<=500, 1<=m<=2000), the number of caves and passages. Each of the following m lines contains four integers u, v, di and ai (1<=u,v<=n, 1<=di<=1000, 0<=ai<=1000). Note that there can be multiple passages connecting the same pair of caves, and even passages connecting a cave and itself.
Output
For each test case, print the case number and the minimal total difficulty.
Sample Input
4 4
1 2 5 1
2 4 6 0
1 3 4 0
3 4 9 1
4 4
1 2 5 10
2 4 6 10
1 3 4 10
3 4 9 10
Sample Output
Case 1: 23
Case 2: 24
HINT
这本是湖南省一次省赛中的题目,因为自己学校的oj无法提交了,只好在vua上提交了。。。
思路:在没学网络流之前还以为是个最短路问题,然后wa了n发,后来才知道是一个最小费用最大流问题。这里讲将困难度看做费用,再为每一条边上为1的流量,然后将1节点连到源点,流量为2,费用为0,将n连到汇点,流量为2,费用为0,这样求出最小费用最大流就是题目所求
#include <iostream>
#include <stdio.h>
#include <cstring>
#include <vector>
#include <queue>
#define INF 0x3f3f3f3f
using namespace std;
const int maxn = 666;
struct Edge
{
int from,to,cap,flow,cost;
Edge(){}
Edge(int a,int b,int c,int d,int e):from(a),to(b),cap(c),flow(d),cost(e){}
};
struct MCMF
{
int n,m,s,t;
vector<Edge> edges;
vector<int> g[maxn];
int inq[maxn];
int d[maxn];
int p[maxn];
int a[maxn];
void init(int n)
{
this->n =n;
for(int i=0;i<n;i++)g[i].clear();
edges.clear();
}
void addedge(int from,int to,int cap,int cost)
{
Edge e1= Edge(from,to,cap,0,cost), e2= Edge(to,from,0,0,-cost);
edges.push_back(e1);
edges.push_back(e2);
m=edges.size();
g[from].push_back(m-2);
g[to].push_back(m-1);
}
bool spfa(int s,int t, int & flow,int & cost)
{
for(int i=0;i<n;i++)
d[i]=INF;
memset(inq,0,sizeof(inq));
d[s]=0;
inq[s]=1;
p[s]=0;
a[s]=INF;
queue<int>q;
q.push(s);
while(!q.empty())
{
int u=q.front();
q.pop();
inq[u]=0;
for(int i=0;i<g[u].size();i++)
{
Edge & e = edges[g[u][i]];
if(e.cap>e.flow && d[e.to]>d[u]+e.cost)
{
d[e.to]=d[u]+e.cost;
p[e.to]=g[u][i];
a[e.to]=min(a[u],e.cap-e.flow);
if(!inq[e.to])
{
q.push(e.to);
inq[e.to]=1;
}
}
}
}
if(d[t]==INF)
return false;
flow+=a[t];
cost+=a[t]*d[t];
int u=t;
while(u!=s)
{
edges[p[u]].flow+=a[t];
edges[p[u]^1].flow-=a[t];
u=edges[p[u]].from;
}
return true;
}
int Mincost(int s,int t)
{
int flow=0,cost =0;
while(spfa(s,t,flow,cost));
return cost;
}
}sol;
int main()
{
//freopen("in.txt","r",stdin);
int n,m,cas=1;
while(scanf("%d%d",&n,&m)!=EOF)
{
//printf("%d %d",n,m);
int s=0,t=n+1;
sol.init(n+2);
while(m--)
{
int u,v,c,ad;
scanf("%d%d%d%d",&u,&v,&c,&ad);
//printf(" %d%d%d%d\n",u,v,c,ad);
sol.addedge(u,v,1,c);
sol.addedge(u,v,1,c+ad);
}
sol.addedge(s,1,2,0);
sol.addedge(n,t,2,0);
printf("Case %d: %d\n",cas++,sol.Mincost(s,t));
}
}