紫书 例题11-10 UVa 1349 (二分图最小权完美匹配)

二分图网络流做法

(1)最大基数匹配。源点到每一个X节点连一条容量为1的弧, 每一个Y节点连一条容量为1的弧, 然后每条有向

边连一条弧, 容量为1, 然后跑一遍最大流即可, 最大流即是最大匹配对数

(2)最小(大)权完美匹配(每个点都被匹配到)。和最大基数匹配类似, 只是有向边的权值就是费用, 其余弧费用为0.

跑一遍最小费用流。最后要判断从s出发的弧是否满载, 不是则不能完美匹配。如果求最大权那么费用设为负的就ok。

这道题目每一个点恰好在一个圈内, 也就是说每一个点只有唯一的后继。反过来, 如果每一个点只有唯一的后继

那么每一个点恰好属于一个圈。那么就是每一个点要 匹配其唯一的后继, 那么这就成了二分图匹配问题。

因为要二分图, 所以拆点, 每个点拆成xi和yi, 然后a与b连接的时候xa连yb, 这样就变成了二分图最小权完美匹配。

#include<cstdio>
#include<vector>
#include<queue>
#include<algorithm>
#include<cstring> 
#define REP(i, a, b) for(int i = (a); i < (b); i++)
using namespace std;

typedef long long ll;
const int MAXN = 212;
struct Edge
{
	int from, to, cap, flow, cost;
	Edge(int from, int to, int cap, int flow, int cost) : from(from), to(to), cap(cap), flow(flow), cost(cost) {};
};
vector<Edge> edges;
vector<int> g[MAXN];
int p[MAXN], a[MAXN], d[MAXN], vis[MAXN], n, m, s, t;

void AddEdge(int from, int to, int cap, int cost)
{
	edges.push_back(Edge(from, to, cap, 0, cost));
	edges.push_back(Edge(to, from, 0, 0, -cost));
	g[from].push_back(edges.size() - 2);
	g[to].push_back(edges.size() - 1);
}

bool spfa(int& flow, ll& cost)  
{
	REP(i, 0, t + 1) d[i] = (i == s ? 0 : 1e9);
	memset(vis, 0, sizeof(vis));
	a[s] = 1e9; vis[s] = 1; p[s] = 0; 
	
	queue<int> q;
	q.push(s);
	while(!q.empty())
	{
		int u = q.front(); q.pop();
		vis[u] = 0;
		REP(i, 0, g[u].size())
		{
			Edge& e = edges[g[u][i]];
			if(e.cap > e.flow && d[e.to] > d[u] + e.cost)
			{
				d[e.to] = d[u] + e.cost;
				p[e.to] = g[u][i];
				a[e.to] = min(a[u], e.cap - e.flow);
				if(!vis[e.to]) { vis[e.to] = 1; q.push(e.to); }
			}
		}
	}
	
	if(d[t] == 1e9) return false;
	flow += a[t]; 
	cost += d[t] * a[t];
	for(int u = t; u != s; u = edges[p[u]].from)
	{
		edges[p[u]].flow += a[t]; 
		edges[p[u] ^ 1].flow -= a[t];
	}
	return true;
}

int mincost(ll& cost)
{
	int flow = 0; cost = 0;
	while(spfa(flow, cost));
	return flow;
}

int main()
{
	while(~scanf("%d", &n) && n)
	{
		s = 0; t = 2 * n + 1;
		REP(i, 0, t + 1) g[i].clear();
		edges.clear();
		
		for(int i = 1; i <= n; i++)
		{
			AddEdge(s, i, 1, 0);
			AddEdge(n + i, t, 1, 0);	
		}
		
		for(int i = 1; i <= n; i++)
		{
			while(1)
			{
				int j, d;
				scanf("%d", &j);
				if(j == 0) break;
				scanf("%d", &d);
				AddEdge(i, n + j, 1, d);
			}
		}	
		
		ll ans, flow;
		flow = mincost(ans);
		if(flow != n) puts("N");
		else printf("%lld\n", ans);
	} 

	return 0;
} 

猜你喜欢

转载自blog.csdn.net/qq_34416123/article/details/80469457