題目鏈接
題意:首先有n1,表示有n1個插座,每個插座屬於一種類型(有可能是多個插座是同一類型)
然後有n2,表示有n2個設備,每個設備的插頭屬於一種類型,與插座對應類型的就可以充電。
接着有n3,表示有n3種轉換器,比如A和B,表示可以將A類型的插頭轉成B類型的插頭。
要我們求出這n2個設備有多少不能充上電
分析:首先,虛擬出超級源點st和超級匯點la,然後對於每個插座,都建一條插座到匯點流量爲1的邊,對所有設備都建立一條源點到設備流量爲1的邊,還有對於每一個設備,其可以直接對應的插座直接建一條流量爲1的邊,對所有的插頭A–>插頭B建一條inf的邊(因爲轉換器有無數個)
建完就跑一個最大流就行了,然後將設備的總數減去最大流就行了。
代碼:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <queue>
#include <set>
#include <map>
#include <algorithm>
#include <math.h>
#include <vector>
using namespace std;
typedef long long ll;
const int mod=1e9+7;
const int maxn=5005+10;
const int maxm=100005;
const int inf=0x3f3f3f3f;
struct node {
int v,nex,cap,flow;
};
struct Dinic{
int head[maxn];
int st,la;//源點和匯點
int vis[maxn],tot;
node edge[maxn];
void init(){
tot=0;
memset (head,-1,sizeof (head));
}
void addedge(int u,int v,int c){
edge[tot]=node{v,head[u],c,0};
head[u]=tot++;
edge[tot]=node{u,head[v],0,0};
head[v]=tot++;
}
int bfs(){
memset (vis,0,sizeof (vis));
queue<int>q;
q.push(st);
vis[st]=1;
while (!q.empty()){
int u=q.front();q.pop();
for (int i=head[u];i!=-1;i=edge[i].nex){
int v=edge[i].v,cap=edge[i].cap,flow=edge[i].flow;
if(vis[v]==0&&cap>flow){
vis[v]=vis[u]+1;
if (v==la){
return 1;
}
q.push(v);
}
}
}
return 0;
}
int dfs(int u,int flow){
if (u==la||flow==0){
return flow;
}
int ans=0,tmp;
for (int i=head[u];i!=-1;i=edge[i].nex){
int v=edge[i].v,cap=edge[i].cap,f=edge[i].flow;
if ((vis[v]==vis[u]+1)&&(tmp=dfs(v,min(cap-f,flow)))>0){
edge[i].flow+=tmp;
edge[i^1].flow-=tmp;
ans+=tmp;
flow-=tmp;
if (flow==0)break;
}
}
return ans;
}
int maxFlow(int s,int t){
this->st=s;
this->la=t;
int ans=0;
while (bfs()){
while (1){
int tmp=dfs(st,inf);
if (tmp==0)break;
ans+=tmp;
}
}
return ans;
}
}dinic;
int n,m,k;
char mp[505][30];
char str1[30],str2[30];
int cnt=0;
int find(char *str){
for (int i=0;i<cnt;i++){
if (strcmp(str,mp[i])==0)return i;
}
strcpy(mp[cnt++],str);
return cnt-1;
}
int main()
{
dinic.init();
scanf ("%d",&n);
int st=0,la=1;//源點和匯點
for (int i=1;i<=n;i++){
scanf ("%s",str1);
int pos=find(str1);
dinic.addedge(pos+2,la,1);//插座-->匯點
}
scanf ("%d",&m);
for (int i=1;i<=m;i++){
scanf ("%s%s",str1,str2);
int pos1=find(str1);
int pos2=find(str2);
dinic.addedge(st,pos1+2,1);//源點到設備
dinic.addedge(pos1+2,pos2+2,1);//設備到插座
}
scanf ("%d",&k);
for (int i=1;i<=k;i++){
scanf ("%s%s",str1,str2);
int pos1=find(str1);
int pos2=find(str2);
dinic.addedge(pos1+2,pos2+2,inf);//轉換器
}
int ans=dinic.maxFlow(st,la);
printf ("%d\n",m-ans);
return 0;
}