hdu 1853 Cyclic Tour 最小费用最大流

题意:一个有向图,现在问将图中的每一个点都划分到一个环中的最少代价(边权和)。

思路:拆点,建二分图,跑最小费用最大流即可。若最大流为n,则说明是最大匹配为n,所有点都参与,,每个点的入度和出度又是1,所以就是环。

/********************************************************* file name: hdu1853.cpp author : kereo create time: 2015年02月16日 星期一 17时38分51秒*********************************************************/#include<iostream>#include<cstdio>#include<cstring>#include<queue>#include<set>#include<map>#include<vector>#include<stack>#include<cmath>#include<string>#include<algorithm>using namespace std;typedef long long ll;const int sigma_size=26;const int N=200+50;const int MAXN=1000000;const int inf=0x3fffffff;const double eps=1e-8;const int mod=1000000000+7;#define L(x) (x<<1)#define R(x) (x<<1|1)#define PII pair<int, int>#define mk(x,y) make_pair((x),(y))int n,m,edge_cnt,res;int head[N],inq[N],d[N],A[N],pre[N];struct Edge{int v,cap,flow,cost,next;}edge[MAXN<<1];void init(){edge_cnt=0;memset(head,-1,sizeof(head));}void addedge(int u,int v,int cap,int cost){edge[edge_cnt].v=v; edge[edge_cnt].cap=cap; edge[edge_cnt].flow=0;edge[edge_cnt].cost=cost; edge[edge_cnt].next=head[u]; head[u]=edge_cnt++;edge[edge_cnt].v=u; edge[edge_cnt].cap=0; edge[edge_cnt].flow=0;edge[edge_cnt].cost=-cost; edge[edge_cnt].next=head[v]; head[v]=edge_cnt++; } bool spfa(int st,int ed,int &flow,int &cost){memset(inq,0,sizeof(inq));for(int i=0;i<=ed;i++) d[i]=inf;d[st]=0; inq[st]=1; pre[st]=0; A[st]=inf;queue<int>Q;Q.push(st);while(!Q.empty()){int u=Q.front(); Q.pop();inq[u]=0;for(int i=head[u];i!=-1;i=edge[i].next){int v=edge[i].v;if(edge[i].cap>edge[i].flow && d[v]>d[u]+edge[i].cost){d[v]=d[u]+edge[i].cost; pre[v]=i;A[v]=min(A[u],edge[i].cap-edge[i].flow);if(!inq[v]){Q.push(v);inq[v]=1;}}}}if(d[ed] == inf)return false;flow+=A[ed]; cost+=A[ed]*d[ed];int u=ed;while(u!=st){edge[pre[u]].flow+=A[ed];edge[pre[u]^1].flow-=A[ed];u=edge[pre[u]^1].v;}return true; } int MinCostFlow(int st,int ed){int flow=0,cost=0;while(spfa(st,ed,flow,cost)) ;res=flow;return cost; }int main(){int T;while(~scanf("%d%d",&n,&m)){init();for(int i=0;i<m;i++){int u,v,w;scanf("%d%d%d",&u,&v,&w);addedge(u,v+n,1,w);}for(int i=1;i<=n;i++){addedge(0,i,1,0);addedge(i+n,2*n+1,1,0);}int ans=MinCostFlow(0,2*n+1);if(res!=n)ans=-1;printf("%d\n",ans);}return 0;}

伟人之所以伟大,是因为他与别人共处逆境时,

hdu 1853 Cyclic Tour 最小费用最大流

相关文章:

你感兴趣的文章:

标签云: