码迷,mamicode.com
首页 > 其他好文 > 详细

poj 2135 费用流

时间:2015-05-19 14:45:05      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:acm   poj   

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>

using namespace std;
#define MOD 0x3f3f3f3f
#define V 1000 + 10
#define E 10000 + 10

int n, m;
bool vis[V];
int cnt, dist[V], head[V], pre[V];

struct Edge
{
    int u, v, c, cost, next;//This 'c' means cap
} edge[E<<2];

void init()
{
    cnt = 0;
    memset(head, -1, (n+3) * sizeof(int));
}

void adde(int u, int v, int c, int cost)
{
    edge[cnt].u = u;
    edge[cnt].v = v;
    edge[cnt].c = c;
    edge[cnt].cost = cost;
    edge[cnt].next = head[u];
    head[u] = cnt++;

    edge[cnt].u = v;
    edge[cnt].v = u;
    edge[cnt].c = 0;
    edge[cnt].cost = -cost;
    edge[cnt].next = head[v];
    head[v] = cnt++;
}

bool spfa(int begin, int end)
{
    int u, v;
    queue<int> q;
    memset(pre, -1, (n+3)*sizeof(int));
    memset(vis, 0, (n+3)*sizeof(bool));
    memset(dist, 0x3f, (n+3)*sizeof(int));
    vis[begin] = 1;
    dist[begin] = 0;
    q.push(begin);
    while(!q.empty())
    {
        u = q.front();
        q.pop();
        vis[u] = false;
        for(int i=head[u]; i!=-1; i=edge[i].next)
            if(edge[i].c > 0)
            {
                v = edge[i].v;
                if(dist[v] > dist[u] + edge[i].cost)
                {
                    dist[v] = dist[u] + edge[i].cost;
                    pre[v] = i;
                    if(!vis[v])
                    {
                        vis[v] = true;
                        q.push(v);
                    }
                }
            }
    }
    return dist[end] != MOD;
}

int MCMF(int begin, int end)
{
    int ans = 0, flow;
    int flow_sum = 0;
    while(spfa(begin, end))
    {
        flow = MOD;
        for(int i=pre[end]; i!=-1; i=pre[edge[i].u])
            flow = min(flow, edge[i].c);

        for(int i=pre[end]; i!=-1; i=pre[edge[i].u])
        {
            edge[i].c -= flow;
            edge[i^1].c += flow;
        }
        ans += dist[end] * flow;
        flow_sum += flow;
    }
    return ans;
}

int main()
{
    int u, v, c;
    while(~scanf("%d%d", &n, &m))
    {
        init();
        for(int i=0; i<m; i++)
        {
            scanf("%d%d%d", &u, &v, &c);
            adde(u, v, 1, c);
            adde(v, u, 1, c);
        }
        adde(0, 1, 2, 0);
        adde(n, n+1, 2, 0);
        printf("%d\n", MCMF(0, n+1));
    }
    return 0;
}

poj 2135 费用流

标签:acm   poj   

原文地址:http://blog.csdn.net/dojintian/article/details/45843951

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!