题意:有n个英雄, m个怪兽, k瓶药水, 每个英雄都有一个它可以杀的怪物集合, 但只能杀一个, 但如果喝了药水就可以再杀一个,注意每个怪物只能死一次, 每个英雄只能喝一瓶药水。问英雄们最多杀多少怪物。
大概思路:网络流模板题, 只要建出图就可以得到答案,
设置虚点p
S ~P 流量为 k
P~每个英雄 1
S~每个英雄 1
每个英雄~能杀的怪兽集合1
怪兽~终点1
重点:不能S~P n + k, 然后 p ~ 每个英雄 2, 因为这样会导致有可能超过k个人发出了大小为2的流量,与题意不和
细节见于代码
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 2e4 + 10, M = 5e4 + 10, INF = 1e9 + 12;
int n, m, S, T, k;
int h[N], e[M], f[M], ne[M], idx;
int q[N], d[N], cur[N];
void add(int a, int b, int c)
{
e[idx] = b, f[idx] = c, ne[idx] = h[a], h[a] = idx ++;
e[idx] = a, f[idx] = 0, ne[idx] = h[b], h[b] = idx ++;
}
bool bfs()
{
int hh = 0, tt = 0;
memset(d, -1, sizeof d);
q[0] = S, d[S] = 0, cur[S] = h[S]; //cur当前弧优化存的是S点对应的下一层的点的可能可用的第一个边的编号
while(hh <= tt)
{
int t = q[hh ++];
for(int i = h[t]; ~i; i = ne[i])
{
int ver = e[i];
if(d[ver] == -1 && f[i])
{
d[ver] = d[t] + 1;
cur[ver] = h[ver];
if(ver == T) return true;
q[++ tt] = ver;
}
}
}
return false;
}
int find(int u, int limit)
{
if(u == T) return limit;
int flow = 0;
for(int i = cur[u]; ~i && flow < limit; i = ne[i])
{
cur[u] = i;//当前弧优化
int ver = e[i];
if(d[ver] == d[u] + 1 && f[i])
{
int t = find(ver, min(f[i], limit - flow));
if(!t) d[ver] = -1;
f[i] -= t, f[i^1] += t, flow += t;
}
}
return flow;
}
int dinic()
{
int r = 0, flow;
while(bfs()) while(flow = find(S, INF)) r += flow;
return r;
}
int main()
{
// freopen("C:\\Users\\86183\\Desktop\\out.TXT","r", stdin);
// freopen("C:\\Users\\86183\\Desktop\\in.TXT","wb", stdout);
while(~scanf("%d%d%d", &n, &m, &k))
{
memset(h, -1, sizeof h);
idx = 0;
int sum = n + m;
S = sum + 1, T = sum + 2;
int P = sum + 3;
add(S, P, k);
for(int i = 1; i <= n; i ++)
{
int t;
scanf("%d", &t);
for(int j = 1; j <= t; j ++)
{
int x;
scanf("%d", &x);
add(i, n + x, 1);
}
}
for(int i = 1; i <= n; i++)
add(S, i, 1), add(P, i, 1);
for(int i = n + 1; i <= n + m; i ++)
{
add(i, T, 1);
}
printf("%d\n", dinic());
}
return 0;
}
匈牙利匹配
#include <bits/stdc++.h>
using namespace std;
const int N = 505;
int n, m, k, a[N * 2][N], b[N], girl[N];
bool find(int x)
{
for(int j = 1; j <= m; j ++)
{
if(a[x][j] == 1 && b[j] == 0)
{
b[j] = 1;
if(girl[j] == 0 || find(girl[j]))
{
girl[j] = x;
return true;
}
}
}
return false;
}
int main()
{
cin >> n >> m >> k;
for(int i = 1; i <= n; i++)
{
int s, x;
cin >> s;
for(int j = 1; j <= s; j ++)
{
scanf("%d", &x);
a[i][x] = 1;
a[i + n][x] = 1;
}
}
int sum = 0, sum1 = 0;
for(int i = 1; i <= n * 2; i ++)
{
memset(b, 0, sizeof b);
if(find(i))
{
if(i <= n) sum ++;
else sum1 ++;
}
}
cout << sum + min(k, sum1) << endl;
return 0;
}