//author: CHC
//First Edit Time: 2014-10-20 10:45
//Last Edit Time: 2014-10-21 16:11
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <set>
#include <vector>
#include <map>
#include <queue>
#include <set>
#include <algorithm>
#include <limits>
using namespace std;
typedef long long LL;
const int MAXN=1e+4;
const int MAXM=1e+5;
const int INF= numeric_limits<int>::max();
const LL LL_INF= numeric_limits<LL>::max();
struct Edge
{
int from,to,ci,cost,next;
Edge(){}
Edge(int _from,int _to,int _ci,int _cost,int _next):from(_from),to(_to),ci(_ci),cost(_cost),next(_next){}
}e[MAXM];
int head[MAXN],tot;
int q[MAXM];
int dis[MAXN],pre[MAXN],rec[MAXN],vis[MAXN];
inline void init(){
memset(head,-1,sizeof(head));
tot=0;
}
inline void AddEdge1(int u,int v,int ci,int cost){
e[tot]=Edge(u,v,ci,cost,head[u]);
head[u]=tot++;
e[tot]=Edge(v,u,0,-cost,head[v]);
head[v]=tot++;
}
inline bool spfa(int S,int T,LL &cost,LL &flow){
int i,h=0,t=0;
for(i=0;i<=MAXN;i++){
dis[i]=INF;
vis[i]=false;
}
q[h]=S;
dis[S]=0;
vis[S]=true;
while(h<=t){
int u=q[h++];
vis[u]=false;
for(i=head[u];~i;i=e[i].next){
int v=e[i].to;
if(e[i].ci>0&&dis[v]>dis[u]+e[i].cost){
dis[v]=dis[u]+e[i].cost;
pre[v]=u;
rec[v]=i;
if(!vis[v]){
vis[v]=1;
q[++t]=v;
}
}
}
}
if(dis[T]==INF)return false;
int minn=INF;
for(i=T;i!=S;i=pre[i]){
if(e[rec[i]].ci<minn)
minn=e[rec[i]].ci;
}
for(i=T;i!=S;i=pre[i]){
//cost+=minn*e[rec[i]].cost;
e[rec[i]].ci-=minn;
e[rec[i]^1].ci+=minn;
}
cost+=dis[T]*minn;
flow+=minn;
return true;
}
inline void mincostmaxflow(int S,int T,LL &cost,LL &flow){
while(spfa(S,T,cost,flow));
}
struct point {
int to,v;
point(){}
point(int _to,int _v):to(_to),v(_v){}
};
vector <point> ex[MAXN];
int st,et,target=0;
void dfs(int now,int preval){
int sum=0;
for(int i=0;i<(int)ex[now].size();i++){
point tmp=ex[now][i];
dfs(tmp.to,tmp.v);
sum+=tmp.v;
//Y[i]
AddEdge1(now,tmp.to,INF,0);
}
int cc=preval-sum;
//s t
if(cc>0)AddEdge1(st,now,cc,0),target+=cc;
else AddEdge1(now,et,-cc,0);
}
int main()
{
int t,cas=0,n,m;
scanf("%d",&t);
while(t--){
scanf("%d",&n);
st=n+10;
et=n+11;
init();
target=0;
for(int i=0;i<=n;i++)ex[i].clear();
for(int i=0,x,y,w;i<n-1;i++){
scanf("%d%d%d",&x,&y,&w);
ex[y].push_back(point(x,w));
}
scanf("%d",&m);
for(int i=0,u,v,l,c;i<m;i++){
scanf("%d%d%d%d",&u,&v,&l,&c);
AddEdge1(u,v,l,c);
}
dfs(1,0);
LL cost=0,flow=0;
mincostmaxflow(st,et,cost,flow);
printf("Case #%d: ",++cas);
if(target==flow){
printf("%I64d\n",cost);
}
else puts("-1");
}
scanf(" ");
return 0;
}
HDU 3947 River Problem 费用流
最新推荐文章于 2019-07-10 13:05:31 发布