zoukankan      html  css  js  c++  java
  • ACM/ICPC 之 电力网络-EK算法(POJ1459)

      按照电站发电(从源点到电站),消费者消费(从消费者到汇点)的想法构建网络,以下是EK解法

    //网络流EK算法
    //Time:922Ms    memory:224K
    #include<iostream>
    #include<cstring>
    #include<cstdio>
    #include<algorithm>
    #include<queue>
    using namespace std;
    
    #define MAX 105
    #define INF 0x3f3f3f3f
    
    int n,np,nc,m;
    int s,t;
    int res[MAX][MAX];  //残留网络
    int pre[MAX];
    
    bool bfs()
    {
        memset(pre,-1,sizeof(pre));
        queue<int> q;
        q.push(s);  pre[s] = 0;
        while(!q.empty()){
            int cur = q.front();
            q.pop();
            for(int i = 1; i <= t; i++)
            {
                if(pre[i] == -1 && res[cur][i])
                {
                    pre[i] = cur;
                    if(i == t) return true;
                    q.push(i);
                }
            }
        }
        return false;
    }
    
    int EK()
    {
        int maxFlow = 0;
        while(bfs()){
            int alpha = INF;    //最小可改进量
            for(int i = t; i != s; i = pre[i])
                alpha = min(alpha, res[pre[i]][i]);
            for(int i = t; i != s; i = pre[i])
            {
                res[pre[i]][i] -= alpha;
                res[i][pre[i]] += alpha;
            }
            maxFlow += alpha;
        }
        return maxFlow;
    }
    
    int main()
    {
    	//freopen("in.txt", "r", stdin);
    
    	while(~scanf("%d%d%d%d", &n,&np,&nc,&m)){
            s = 0;  t = n+2;
            memset(res,0,sizeof(res));
            int a,b,c;
            while(m--){
                scanf(" (%d,%d)%d", &a,&b,&c);
                res[a+1][b+1] = c;
            }
            for(int i = 0; i < np; i++)
            {   //电站
                scanf(" (%d)%d", &b,&c);
                res[s][b+1] = c;
            }
            for(int i = 0; i < nc; i++)
            {   //消费
                scanf(" (%d)%d", &a,&c);
                res[a+1][t] = c;
            }
    
            printf("%d
    ", EK());
    
    	}
    
    	return 0;
    }
    
  • 相关阅读:
    洛谷 P1941 飞扬的小鸟
    洛谷P2464 [SDOJ2008]郁闷的小J
    [cogs2314][HZOI 2015] Persistable Editor
    [vijos1067]Warcraft III 守望者的烦恼
    【vijos1049】送给圣诞夜的礼品
    [cogs347]地震
    gcc 编译多个源文件
    2_兔子产仔问题
    1_鸡兔同笼问题
    LeetCode(61) Rotate List
  • 原文地址:https://www.cnblogs.com/Inkblots/p/5707074.html
Copyright © 2011-2022 走看看