【最大匹配】人员分配

L i n k Link

S S L   1338 SSL\ 1338

D e s c r i p t i o n Description

设有M个工人x1, x2, …, xm,和N项工作y1, y2, …, yn,规定每个工人至多做一项工作,而每项工作至多分配一名工人去做。由于种种原因,每个工人只能胜任其中的一项或几项工作。问应怎样分配才能使尽可能多的工人分配到他胜任的工作。这个问题称为人员分配问题。

I n p u t Input

第一行两个整数m,n分别为工人数和工作数。
接下来一个整数s,为二分图的边数。
接下来s行,每行两个数ai,bi表示第ai个工人能胜任第bi份工作

O u t p u t Output

一个整数,表示最多能让多少个工人派到自己的胜任的工作上。

S a m p l e Sample I n p u t Input

3 3
4
1 2
2 1
3 3
1 3

S a m p l e Sample O u t p u t Output

3

H i n t Hint

规模:
1<=m,n<=100
1<=s<=10000

T r a i n Train o f of T h o u g h t Thought

直接用匈牙利算法求最大匹配(邻接矩阵 or 邻接表)
还可以用网络流(蒟蒻尚未敲出)

C o d e s Codes

邻接矩阵

#include<iostream>
#include<cstring>
#include<cstdio>

using namespace std;
int q, n, m, s, ans;
int c[105], link[10005], f[105][105];

bool find(int x)
{
	for (int i = 1; i <= n; ++i)
		if (f[x][i] && !c[i])
		{
			c[i] = true;
			q = link[i];
			link[i] = x;
			if (q == 0 || find(q)) return 1;
			link[i] = q;
		}
	return 0;
}

int main()
{
	scanf("%d%d", &n, &m); scanf("%d", &s);
	for (int i = 1; i <= s; ++i)
	{
		int a, b;
		scanf("%d%d", &a, &b);
		f[a][b] = 1;                
	}
	for (int i = 1; i <= n; ++i) 
	{
		memset(c, 0, sizeof(c));
		if (find(i)) ans++;
	}
	printf("%d", ans);
}

邻接表

#include<iostream>
#include<cstring>
#include<cstdio>

using namespace std;
int q, n, m, s, ans, t;
int c[105], h[105], link[105], f[105][105];

struct node
{
	int to, next;
}g[10005];

void add(int a, int b)
{g[++t] = (node){b, h[a]}; h[a] = t;}

bool find(int x)
{
	for (int i = h[x]; i; i = g[i].next)
	{
		if (!c[g[i].to])
		{
			c[g[i].to] = 1;
			q = link[g[i].to];
			link[g[i].to] = x;
			if (q == 0 || find(q)) return 1;
			link[g[i].to] = q;
		}
	}
	return 0;
}

int main()
{
	scanf("%d%d", &n, &m); scanf("%d", &s);
	for (int i = 1; i <= s; ++i)
	{
		int a, b;
		scanf("%d%d", &a, &b);
		add(a, b);             
	}
	for (int i = 1; i <= n; ++i) 
	{
		memset(c, 0, sizeof(c));
		if (find(i)) ans++;
	}
	printf("%d", ans);
}

猜你喜欢

转载自blog.csdn.net/LTH060226/article/details/104015380
今日推荐