标签:最大权值匹配
链接:http://acm.hdu.edu.cn/showproblem.php?pid=1853
6 9 1 2 5 2 3 5 3 1 10 3 4 12 4 1 8 4 6 11 5 4 7 5 6 9 6 5 4 6 5 1 2 1 2 3 1 3 4 1 4 5 1 5 6 1
42 -1HintIn the first sample, there are two cycles, (1->2->3->1) and (6->5->4->6) whose length is 20 + 22 = 42.
题意:
给你若干个点和带权有向边,要求把所有点连成环,可以多个环,但是每个环至少要有两个点。
做法:
所有的点成环,可以知道所有的点 入度和出度都为1。并且只要符合这个条件,所有点肯定是在一个环中的,也就是符合条件了。
所以可以建一个二分图,左边的点从s流入费用为0,流量为1,表示入度为1 ,右边一样。
然后根据边 建流量为1,费用为边权的边,这就是最大权值匹配的图了。
这样只要满流就符合条件了。
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
//最小费用最大流,求最大费用只需要取相反数,结果取相反数即可。
//点的总数为 N,点的编号 0~N-1
const int MAXN = 10000;
const int MAXM = 100000;
const int INF = 0x3f3f3f3f;
struct Edge
{
int to,next,cap,flow,cost;
}edge[MAXM];
int head[MAXN],tol;
int pre[MAXN],dis[MAXN];
bool vis[MAXN];
int N;//节点总个数,节点编号从0~N-1
void init(int n)
{
N = n;
tol = 0;
memset(head,-1,sizeof(head));
}
void addedge(int u,int v,int cap,int cost)
{
edge[tol].to = v;
edge[tol].cap = cap;
edge[tol].cost = cost;
edge[tol].flow = 0;
edge[tol].next = head[u];
head[u] = tol++;
edge[tol].to = u;
edge[tol].cap = 0;
edge[tol].cost = -cost;
edge[tol].flow = 0;
edge[tol].next = head[v];
head[v] = tol++;
}
bool spfa(int s,int t)
{
queue<int>q;
for(int i = 0;i < N;i++)
{
dis[i] = INF;
vis[i] = false;
pre[i] = -1;
}
dis[s] = 0;
vis[s] = true;
q.push(s);
while(!q.empty())
{
int u = q.front();
q.pop();
vis[u] = false;
for(int i = head[u]; i != -1;i = edge[i].next)
{
int v = edge[i].to;
if(edge[i].cap > edge[i].flow &&
dis[v] > dis[u] + edge[i].cost )
{
dis[v] = dis[u] + edge[i].cost;
pre[v] = i;
if(!vis[v])
{
vis[v] = true;
q.push(v);
}
}
}
}
if(pre[t] == -1)return false;
else return true;
}
//返回的是最大流, cost存的是最小费用
int minCostMaxflow(int s,int t,int &cost)
{
int flow = 0;
cost = 0;
while(spfa(s,t))
{
int Min = INF;
for(int i = pre[t];i != -1;i = pre[edge[i^1].to])
{
if(Min > edge[i].cap - edge[i].flow)
Min = edge[i].cap - edge[i].flow;
}
for(int i = pre[t];i != -1;i = pre[edge[i^1].to])
{
edge[i].flow += Min;
edge[i^1].flow -= Min;
cost += edge[i].cost * Min;
}
flow += Min;
}
return flow;
}
int main()
{
int n,m;
while(scanf("%d%d",&n,&m)!=EOF)
{
init(2*n+2);
int ss=0;
int ee=2*n+1;
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(ss,i,1,0);
addedge(i+n,ee,1,0);
}
int cost,liu;
liu=minCostMaxflow(ss,ee,cost);
if(liu!=n)
{
puts("-1");
}
else
{
printf("%d\n",cost);
}
}
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
hdu 1853 Cyclic Tour 最大权值匹配 所有点连成环的最小边权和
标签:最大权值匹配
原文地址:http://blog.csdn.net/u013532224/article/details/47042487