题意:在一个会议室里有n种插座,每种插座一个,每个插座只能插一种以及一个电器(或者适配器),有m个电器,每个电器有一个插头需要插在相应一种插座上,不是所有电器都能在会议室找到相应插座,有k种适配器,每种适配器可以有无限多数量,每种适配器(a, b)可以把b类插座变为a类插座,问最后有多少个电器无法使用。
建图:其实最初的n个电器不是全部,可能由适配器转换出来别的,也可能有电器需要的但是在n中不存在的,所以我们需要需要先输入,有两种选择,第一拟定一个汇点,这个点要足够大(要容得下所有的点),或者先输入完,最后得出汇点的值。用源点连接插座,权值为1,插座连接电器,权值为1,电器连接汇点,权值为1.插头连接插头,权值为INF。
坑死我了,看样例还以为插座只是字母,结果是字符串。还是读题不认真。代码如下:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <set>
#include <map>
#include <stack>
#include <queue>
#define INF 0x3f3f3f3f
#define ll long long
using namespace std;
const int inf = 0x3f3f3f3f;
const int maxn = 1005;
const int maxm = 1000005;
int n, m;//点数、边数
int sp, tp;//原点、汇点
map<string, int> hash;
struct node {
int u;
int v, next;
int cap;
}mp[maxm];
int pre[maxn], dis[maxn], cur[maxn];//cur为当前弧优化,dis存储分层图中每个点的层数(即到原点的最短距离),pre建邻接表
int cnt = 0;
char str1[30],str2[30];
void init() { //不要忘记初始化
cnt = 0;
memset(pre, -1, sizeof(pre));
}
void add(int u, int v, int w) { //加边
mp[cnt].u = u;
mp[cnt].v = v;
mp[cnt].cap = w;
mp[cnt].next = pre[u];
pre[u] = cnt++;
mp[cnt].u = v;
mp[cnt].v = u;
mp[cnt].cap = 0;
mp[cnt].next = pre[v];
pre[v] = cnt++;
}
bool bfs() { //建分层图
memset(dis, -1, sizeof(dis));
queue<int>q;
while(!q.empty())
q.pop();
q.push(sp);
dis[sp] = 0;
int u, v;
while(!q.empty()) {
u = q.front();
q.pop();
for(int i = pre[u]; i != -1; i = mp[i].next) {
v = mp[i].v;
if(dis[v] == -1 && mp[i].cap > 0) {
dis[v] = dis[u] + 1;
q.push(v);
if(v == tp)
break;
}
}
}
return dis[tp] != -1;
}
int dfs(int u, int cap) {//寻找增广路
if(u == tp || cap == 0)
return cap;
int res = 0, f;
for(int &i = cur[u]; i != -1; i = mp[i].next) {//
int v = mp[i].v;
if(dis[v] == dis[u] + 1 && (f = dfs(v, min(cap - res, mp[i].cap))) > 0) {
mp[i].cap -= f;
mp[i ^ 1].cap += f;
res += f;
if(res == cap)
return cap;
}
}
if(!res)
dis[u] = -1;
return res;
}
int dinic() {
int ans = 0;
while(bfs()) {
for(int i = sp; i <= tp; i++)
cur[i] = pre[i];
ans += dfs(sp, inf);
}
return ans;
}
int main()
{
int k;
while(~scanf("%d",&n))
{
init();
sp = 0;
tp = 500;
int t = 1;
for(int i = 0; i < n; i++)
{
scanf("%s", str1);
if(hash[str1] == 0)
{
hash[str1] = t;
add(t++, tp, 1);
}
}
scanf("%d", &m);
for(int i = 0; i < m; i++)
{
scanf("%s%s", str1, str2);
add(sp, t++, 1);
if(hash[str2] == 0)
{
hash[str2] = t;
add(t - 1, t, 1);
t++;
}
else add(t - 1, hash[str2], 1);
}
scanf("%d", &k);
for(int i = 0; i < k; i++)
{
scanf("%s%s", str1, str2);
if(hash[str1] == 0)
hash[str1] = t++;
if(hash[str2] == 0)
hash[str2] = t++;
add(hash[str1], hash[str2], inf);
}
t++;
printf("%d\n",m - dinic());
}
return 0;
}