PAT T1003 Universal Travel Sites

网络流模板~

#include<bits/stdc++.h>
using namespace std;
const int maxn=1014;
const int inf=1e9;
queue<int> q;
int M,N;
int g[maxn][maxn];
int pre[maxn];
int flow[maxn];
int maxflow;
unordered_map<string,int> pos;
int bfs (int s,int t) {
    while (!q.empty()) q.pop();
    for (int i=1;i<=N;i++) pre[i]=-1;
    pre[s]=0;
    q.push(s);
    flow[s]=inf;
    while (!q.empty()) {
        int x=q.front();
        q.pop();
        if (x==t) break;
        for (int i=1;i<=N;i++) {
            if (g[x][i]>0&&pre[i]==-1) {
                pre[i]=x;
                flow[i]=min(flow[x],g[x][i]);
                q.push(i);
            }
        }
    }
    if (pre[t]==-1) return -1;
    else return flow[t];
} 
void Edmonds_Karp (int s,int t) {
    int increase=0;
    while ((increase=bfs(s,t))!=-1) {
        int k=t;
        while (k!=s) {
            int last=pre[k];
            g[last][k]-=increase;
            g[k][last]+=increase;
            k=last;
        }
        maxflow+=increase;
    }
} 
int main () {
    string s1,s2;
    cin>>s1>>s2>>M;
    pos[s1]=1;
    pos[s2]=2;
    int cnt=3,x;
    for (int i=0;i<M;i++) {
        cin>>s1>>s2>>x;
        if (pos[s1]==0) pos[s1]=cnt++;
        if (pos[s2]==0) pos[s2]=cnt++;
        g[pos[s1]][pos[s2]]=x;
    }
    N=cnt-1;
    Edmonds_Karp (1,2);
    printf ("%d",maxflow);
    return 0;
}

 

posted @ 2020-02-13 11:21  zlc0405  阅读(367)  评论(0编辑  收藏  举报