放牧代码和思想
专注自然语言处理、机器学习算法
    This thing called love. Know I would've. Thrown it all away. Wouldn't hesitate.

POJ 1274 The Perfect Stall 题解 《挑战程序设计竞赛》

目录

POJ 1274 The Perfect Stall

二分图完美匹配:N头牛M个牛栏,每头牛只愿独占特定几个牛栏,求最大分配。

3.5借助水流解决问题的网络流 

二分图匹配

赤裸裸的二分图匹配,转化为最大流问题解决,实现上可以用下面的简化算法:

#include <iostream>
#include <vector>
using namespace std;

#define MAX_V 200 * 2 + 16
int V;					// 顶点数
vector<int> G[MAX_V];	// 图的邻接表
int match[MAX_V];		// 所匹配的顶点
bool used[MAX_V];		// DFS中用到的访问标记

// 向图中增加一条连接u和v的边
void add_edge(int u, int v)
{
	G[u].push_back(v);
	G[v].push_back(u);
}

// 通过DFS寻找增广路
bool dfs(int v)
{
	used[v] = true;
	for (vector<int>::iterator it = G[v].begin(); it != G[v].end(); ++it)
	{
		int u = *it, w = match[u];
		if (w < 0 || !used[w] && dfs(w))
		{
			match[v] = u;
			match[u] = v;
			return true;
		}
	}

	return false;
}

// 求解二分图的最大匹配
int bipartite_matching()
{
	int res = 0;
	memset(match, -1, sizeof(match));
	for (int v = 0; v < V; ++v)
	{
		if (match[v] < 0)
		{
			memset(used, 0, sizeof(used));
			if (dfs(v))
			{
				++res;
			}
		}
	}

	return res;
}

///////////////////////////SubMain//////////////////////////////////
int main(int argc, char *argv[])
{
#ifndef ONLINE_JUDGE
	freopen("in.txt", "r", stdin);
	freopen("out.txt", "w", stdout);
#endif
	int N, M;
	while (scanf("%d%d", &N, &M) != EOF)
	{
		V = N + M;
		for (int i = 0; i < V; ++i)
		{
			G[i].clear();
		}
		for (int i = 0; i < N; ++i)
		{
			int S;
			scanf("%d", &S);
			for (int j = 0; j < S; ++j)
			{
				int u;
				scanf("%d", &u);
				u = N + u - 1;
				add_edge(i, u);
			}
		}

		printf("%d\n", bipartite_matching());
	}
#ifndef ONLINE_JUDGE
	fclose(stdin);
	fclose(stdout);
	system("out.txt");
#endif
	return 0;
}
///////////////////////////End Sub//////////////////////////////////
13785806 hankcs 1274 Accepted 184K 0MS C++ 1596B 2015-01-16 21:08:19

知识共享许可协议 知识共享署名-非商业性使用-相同方式共享码农场 » POJ 1274 The Perfect Stall 题解 《挑战程序设计竞赛》

评论 欢迎留言

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

我的作品

HanLP自然语言处理包《自然语言处理入门》