Paint the Roads UVALive - 2197
网络流·费用流
题目大意:
有n个点,m条边,你的任务是选择其中的一些边,使得每条被选择的边组成一些没有公共边的回路,且每个城市恰好在其中的k个回路上,被选择的边的总权值要求最小。
题解:
每个点在k条回路上意味着每个点的入度和出度都是k。
因此建图:
城市拆点,A、B
源点连向每个城市的A,容量为k,费用0
每个城市的B连向汇点,容量为k,费用0
边连接两个城市(A1->B2),容量为1,费用为权值
满流时,最小费用就是答案。
Code:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#define D(x) cout<<#x<<" = "<<x<<" "
#define E cout<<endl
using namespace std;
const int N = 1005;
const int M = 10005;
const int INF = 0x3f3f3f3f;
int n,m,k,S,T;
int totflow, totcost;
struct Edge{
int from,to,next,cap,flow,cost;
}e[M*2];
int head[N], ec=1;
void clear(){ memset(head,0,sizeof(head)); ec=1; }
void add(int a,int b,int cap,int cost){
ec++; e[ec].to=b; e[ec].from=a;
e[ec].cap=cap; e[ec].flow=0; e[ec].cost=cost;
e[ec].next=head[a]; head[a]=ec;
}
void add2(int a,int b,int cap,int cost){
// cout<<a<<" "<<b<<" "<<cap<<" "<<cost<<endl;
add(a,b,cap,cost); add(b,a,0,-cost);
}
bool vis[N]; int d[N]; int pre[N];
bool spfa(){
memset(vis,false,sizeof(vis));
memset(d,0x3f,sizeof(d));
queue<int> q; q.push(S); d[S]=0; vis[S]=true;
while(!q.empty()){
int u=q.front(); q.pop(); vis[u]=false;
for(int i=head[u];i;i=e[i].next){
int v=e[i].to;
if(d[v]>d[u]+e[i].cost && e[i].cap>e[i].flow){
d[v]=d[u]+e[i].cost; pre[v]=i;
if(!vis[v]){
vis[v]=true; q.push(v);
}
}
}
}
return d[T]!=INF;
}
void mxf(){
int a; totcost=0; totflow=0;
while(spfa()){
a=INF;
for(int pos=T,i=pre[T]; pos!=S; pos=e[i].from,i=pre[pos]){
// D(pos); D(e[i].from); E;
a=min(a,e[i].cap-e[i].flow);
}
// D(a); E;
for(int pos=T,i=pre[T]; pos!=S; pos=e[i].from,i=pre[pos]){
// D(pos); D(e[i].from); E;
e[i].flow+=a; e[i^1].flow-=a; totcost+=e[i].cost*a;
}
totflow+=a;
// D(cost); D(flow); E;
}
}
int main(){
freopen("a.in","r",stdin);
int tt; cin>>tt;
int a,b,c;
while(tt--){
clear();
cin>>n>>m>>k;
S=n*2; T=S+1;
for(int i=0;i<n;i++){
add2(S,i*2,k,0); add2(i*2+1,T,k,0);
}
for(int i=1;i<=m;i++){
scanf("%d%d%d",&a,&b,&c);
add2(a*2,b*2+1,1,c);
}
mxf();
// D(flow); D(cost); E;
// D(n*k); E;
if(totflow==n*k) printf("%d\n",totcost);
else printf("-1\n");
}
}