POJ 1087 最大流

构建最大流模型,因为要求出不能接电数最小,也就是能接电数最大,构建模型,用电器连接源点,电源连接汇点,中间的有边的点都连接起来,取流量为1,因为只能插一次,所以自然取一了,但要注意的是转换器之间是无穷,因为转换器有无穷多个。

直接构好模型,接着套模板就是了。

#include <iostream>
#include <string.h>
#include <queue>
#include<map>
using namespace std;

#define INF 0x3f3f3f3f
#define N 600

int e[N][N];

int S,T;
int n,np,nc,m;
int d[N];

bool bfs(){
    memset(d,-1,sizeof(d));
    queue<int> q;
    q.push(S);
    d[S]=0;
    while(!q.empty()){
        int u=q.front();
        q.pop();
        for(int i=0;i<n;i++){
            if(e[u][i]&&d[i]==-1){
                d[i]=d[u]+1;
                q.push(i);
            }
        }
    }
    return d[T]!=-1;
}

int dfs(int u,int flow){
    if(u==T){
        return flow;
    }
    int res=0;
    for(int i=0;i<n;i++){
        if(e[u][i]&&d[i]==d[u]+1){
            int tmp=dfs(i,min(flow,e[u][i]));
            flow-=tmp;
            e[u][i]-=tmp;
            res+=tmp;
            e[i][u]+=tmp;
            if(flow==0) break;
        }
    }
    if(res==0) d[u]=-1;
    return res;
}

int dinic(){
    int res=0;
    while(bfs()){
        res+=dfs(S,INF);
    }
    return res;
}

int main(){
    string str1,str2;
    S=0,T=N-1;
    ios::sync_with_stdio(false),cin.tie(0);
    while(cin>>n){
        memset(e,0,sizeof(e));
        int sum=1;
        map<string,int> ma;
        while(n--){
            cin>>str1;
            ma[str1]=sum++;
            e[ma[str1]][T]=1;
        }
        cin>>n;m=n;
        while(n--){
            cin>>str1>>str2;
            ma[str1]=sum++;
            if(!ma[str2]){
                ma[str2]=sum++;
            }
            e[ma[str1]][ma[str2]]=1;
            e[S][ma[str1]]=1;
        }
        cin>>n;
        while(n--){
            cin>>str1>>str2;
            if(!ma[str1]) ma[str1]=sum++;
            if(!ma[str2]) ma[str2]=sum++;
            e[ma[str1]][ma[str2]]=INF;
        }
        n=N;
        cout<<m-dinic()<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40679299/article/details/81140086