题目链接:http://vjudge.net/problem/UVA-753
把设备和插座分别看作二分图的左边和右边的点,则问题转换成了求二分图的最大匹配数。因为一个设备的插头类型可以经转换器变成另一种从而可以接到别的插座上,因此先用一遍Floyd算法求出两个插头间是否可以转化,对于能转化的,即从该设备向该插座连一条边。最后的答案为设备数减最大匹配数。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<set>
#include<map>
#include<vector>
#include<queue>
#include<algorithm>
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define lc rt<<1
#define rc rt<<1|1
using namespace std;
typedef long long LL;
const int maxn = 400 + 10;
const int INF = 1e9 + 10;
int d[maxn][maxn]; //某种插头是否可以转换为另一种插头
int device[maxn], target[maxn], temp;
map<string,int> ID;
struct Edge
{
int from, to, cap, flow;
Edge(int u, int v, int c, int f):from(u),to(v),cap(c),flow(f) {}
};
struct EdmondsKarp
{
int n, m;
vector<Edge> edges;
vector<int> G[maxn];
int a[maxn];
int p[maxn];
void init(int n) {
for(int i = 0; i < n; i++) G[i].clear();
}
void AddEdge(int from, int to, int cap) {
edges.push_back(Edge(from, to, cap, 0));
edges.push_back(Edge(to, from, 0, 0));
m = edges.size();
G[from].push_back(m-2);
G[to].push_back(m-1);
}
int Maxflow(int s, int t) {
int flow = 0;
for(;;) {
memset(a, 0, sizeof a);
queue<int> Q;
Q.push(s);
a[s] = INF;
while(!Q.empty()) {
int x = Q.front(); Q.pop();
for(int i = 0; i < G[x].size(); i++) {
Edge& e = edges[G[x][i]];
if(!a[e.to] && e.cap > e.flow) {
p[e.to] = G[x][i];
a[e.to] = min(a[x], e.cap-e.flow);
Q.push(e.to);
}
}
if(a[t]) break;
}
if(!a[t]) break;
for(int u = t; u != s; u = edges[p[u]].from) {
edges[p[u]].flow += a[t];
edges[p[u]^1].flow -= a[t];
}
flow += a[t];
}
return flow;
}
};
int getID(string& s)
{
if (!ID.count(s)) return ID[s] = ++temp;
return ID[s];
}
int main()
{
int T;
int numT, numD, numA;
string s1,s2;
EdmondsKarp My;
scanf("%d",&T);
while(T--) {
temp = 0;
ID.clear();
memset(d, 0, sizeof d);
scanf("%d",&numT);
for(int i = 0; i < numT; i++) {
cin >> s1;
target[i] = getID(s1); //插座
}
scanf("%d",&numD);
for(int i = 0; i < numD; i++) {
cin >> s1 >> s2;
device[i] = getID(s2); //设备
}
scanf("%d",&numA);
for(int i = 0; i < numA; i++) {
cin >> s1 >> s2;
d[getID(s1)][getID(s2)] = 1;
}
//Floyd
int V = ID.size();
for(int k = 1; k <= V; k++)
for(int i = 1; i <= V; i++)
for(int j = 1; j <= V; j++)
d[i][j] |= d[i][k] & d[k][j];
My.init(V+2);
//构建网络
for(int i = 0; i < numD; i++)
for(int j = 0; j < numT; j++)
if(d[device[i]][target[j]]) My.AddEdge(device[i], target[j], INF);
for(int i = 0; i < numD; i++)
My.AddEdge(0, device[i], 1);
for(int i = 0; i < numT; i++)
My.AddEdge(target[i], V+1, 1);
printf("%d\n",numD - My.Maxflow(0, V+1));
if(T) printf("\n");
}
return 0;
}