設有M個工人x1, x2, …, xm,和N項工作y1, y2, …, yn,規定每個工人至多做一項工作,而每項工作至多分配一名工人去做。由於種種原因,每個工人只能勝任其中的一項或幾項工作。問應怎樣分配才能使儘可能多的工人分配到他勝任的工作。這個問題稱爲人員分配問題。
第一行兩個整數m,n分別爲工人數和工作數。
接下來一個整數s,爲二分圖的邊數。
接下來s行,每行兩個數ai,bi表示第ai個工人能勝任第bi份工作
一個整數,表示最多能讓多少個工人派到自己的勝任的工作上。
3 3
4
1 2
2 1
3 3
1 3
3
規模:
1<=m,n<=100
1<=s<=10000
直接用匈牙利算法求最大匹配(鄰接矩陣 or 鄰接表)
還可以用網絡流(蒟蒻尚未敲出)
鄰接矩陣
#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);
}