链接:点击打开链接
题意:给出一个有向图,用一些环覆盖所有点,求所有环的边权和
代码:
#include <math.h>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
using namespace std;
const int INF=0x3f3f3f3f;
struct node{
int to,cap,cost,rev;
};
int V;
int dis[10005],prevv[10005],preve[10005];
vector<node> G[10005];
void addedge(int from,int to,int cap,int cost){
G[from].push_back((node){to,cap,cost,G[to].size()});
G[to].push_back((node){from,0,-cost,G[from].size()-1});
}
int min_cost_flow(int s,int t,int f){
int i,d,v,ans,sign;
ans=0;
while(f>0){
fill(dis,dis+V,INF);
dis[s]=0;
sign=1;
while(sign){
sign=0;
for(v=0;v<V;v++){
if(dis[v]==INF)
continue;
for(i=0;i<G[v].size();i++){
node &e=G[v][i];
if(e.cap>0&&dis[e.to]>dis[v]+e.cost){
dis[e.to]=dis[v]+e.cost;
prevv[e.to]=v;
preve[e.to]=i;
sign=1;
}
}
}
}
if(dis[t]==INF)
return -1;
d=f;
for(v=t;v!=s;v=prevv[v])
d=min(d,G[prevv[v]][preve[v]].cap);
f-=d;
ans+=d*dis[t];
for(v=t;v!=s;v=prevv[v]){
node &e=G[prevv[v]][preve[v]];
e.cap-=d;
G[v][e.rev].cap+=d;
}
}
return ans;
}
int main(){ //有很多这样的题比如hdu4411
int i,t,n,m,u,v,w,ans; //http://blog.csdn.net/stay_accept/article/details/51143446
scanf("%d",&t);
while(t--){ //拆点,一个点表示入度,一个点表示出度
scanf("%d%d",&n,&m); //跑流量是n的费用流
V=2*n+2;
for(i=0;i<=2*n+2;i++)
G[i].clear();
for(i=0;i<m;i++){
scanf("%d%d%d",&u,&v,&w);
addedge(u,v+n,1,w);
}
for(i=1;i<=n;i++){
addedge(0,i,1,0);
addedge(i+n,2*n+1,1,0);
}
ans=min_cost_flow(0,2*n+1,n);
printf("%d\n",ans);
}
return 0;
}