POJ1459 Power Network

POJ1459 网络流模板

#include<cstdio>
#include<algorithm>
#include<queue>
#include<cstring>
#include<map>
using namespace std;
const int maxn=1014;
const int inf=1e9;
queue<int> q;
int n;
int g[maxn][maxn];
int pre[maxn];
int flow[maxn];
int maxflow;
void init () {
    memset (g,0,sizeof(g));
    fill (pre,pre+maxn,0);
    fill (flow,flow+maxn,0);
    maxflow=0; 
}
int bfs (int s,int t) {
    while (!q.empty()) q.pop();
    for (int i=0;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=0;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 () {
    int u,v,z,np,nc,m;
    while (~scanf("%d %d %d %d",&n,&np,&nc,&m)) {
        init ();
        while (m--) {
            while (getchar()!='(');
            scanf ("%d,%d)%d",&u,&v,&z);
            u++;
            v++;
            g[u][v]=z; 
        }
        while (np--) {
            while (getchar()!='(');
            scanf ("%d)%d",&u,&z);
            u++;
            g[0][u]=z;
        }
        while (nc--) {
            while (getchar()!='(');
            scanf ("%d)%d",&u,&z);
            u++;
            g[u][n+1]=z;
        }
        n++;
        Edmonds_Karp (0,n);
        printf ("%d\n",maxflow);
    }
    return 0;
}

 

posted @ 2020-02-16 20:18  zlc0405  阅读(109)  评论(0编辑  收藏  举报