题意:有n个插座,m个插头,k种不同的转换器,只能相同名字的插头和插座才能匹配,问最少剩余多少个插头无法匹配。
题解:最大流问题,建图时可以将汇点的下标位置先保存下来,最后所有型号的字符串都保存完毕,再设一个超级汇点将之前的汇点汇到一起。
#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;
const int N = 500;
const int INF = 0x3f3f3f3f;
int t, n, cap[N][N], m, k, cnt, maxflow, flow[N][N], p[N], a[N];
char str[N][30];
int ek(int en) {
queue<int> q;
memset(flow, 0, sizeof(flow));
maxflow = 0;
while (1) {
memset(a, 0, sizeof(a));
a[0] = INF;
q.push(0);
while (!q.empty()) {
int u = q.front();
q.pop();
for (int v = 0; v <= cnt; v++) {
if (!a[v] && cap[u][v] > flow[u][v]) {
a[v] = a[u] < cap[u][v] - flow[u][v] ? a[u] : cap[u][v] - flow[u][v];
p[v] = u;
q.push(v);
}
}
}
if (a[en] == 0)
break;
for (int i = en; i != 0; i = p[i]) {
flow[p[i]][i] += a[en];
flow[i][p[i]] -= a[en];
}
maxflow += a[en];
}
}
int find(char *p) {
for (int i = 1; i < cnt; i++) {
if (strcmp(str[i], p) == 0)
return i;
}
strcpy(str[cnt], p);
return cnt++;
}
int main() {
scanf("%d", &t);
while (t--) {
scanf("%d", &n);
memset(cap, 0, sizeof(cap));
cnt = 1;
char temp1[30], temp2[30];
for (int i = 1; i <= n; i++) {
scanf("%s", temp1);
int a = find(temp1);
cap[0][a]++;
}
int temp[N];
scanf("%d", &m);
for (int i = 0; i < m; i++) {
scanf("%s%s", temp2, temp1);
temp[i] = find(temp1);
}
scanf("%d", &k);
for (int i = 0; i < k; i++) {
scanf("%s%s", temp1, temp2);
int x1 = find(temp1);
int x2 = find(temp2);
cap[x2][x1] = INF;
}
for (int i = 0; i < m; i++)
cap[temp[i]][cnt]++;
ek(cnt);
printf("%d\n", m - maxflow);
if (t)
printf("\n");
}
return 0;
}