UVa10594 Data Flow(最小费用 最大流)

这道题是一道最小费用最大流问题,从这道题里面,我更加理解什么是最小费用最大流了,主要就是在找最短路径的同时,还要顾及到最大流量及残余网络,其实就是在残余网络中找最短路径

有一下要注意的:

第一,边的两个方向,费用互为相反数

第二,无向图的最小费用最大流,要用邻接表表示,因为点和点之间的两个方向的边要分别表示其反方向,也就是这两边是独立的,不能用互为反边的思想,否则会出现环路,而且会无限循环,SPFA算法就不通了。

还有,提交的时候遇到了submission error,这是服务器忙的反应,和代码没有什么关系,主要是提交不成功

代码:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;

const int N = 110;
const int M = 5500;
const long long INFt = 1000000000000001;
const int INF = 100000000;
int n, m, D, K, id, maxf;
int head[N], from[M], to[M], r[N], p[N];
long long fee[M], ans;
struct edge{
    int to, flow, cap, next;
    long long w;
}e[M*4];
void add( int u, int v, long long w, int c ) {
    e[id].next = head[u], e[id].to = v, e[id].flow = 0, e[id].cap = c, e[id].w = w, head[u] = id++;
}
void init() {
    for ( int i = 1; i <= m; ++i ) scanf("%d%d%lld", &from[i], &to[i], &fee[i]);
    scanf("%d%d", &D, &K);
    id = 0;
    for ( int i = 0; i <= n; ++i ) head[i] = -1;
    for ( int i = 1; i <= m; ++i ) {
        add( from[i], to[i], fee[i], K );
        add( to[i], from[i], -fee[i], 0 );
        add( to[i], from[i], fee[i], K );
        add( from[i], to[i], -fee[i], 0 );
    }
    add( 0, 1, 0, D );
    add( 1, 0, 0, 0 );
}
void mincost() {
    queue<int> q;
    bool inq[N];
    ans = 0;
    maxf = 0;
    long long d[N];
    while( 1 ) {
        memset( inq, 0, sizeof(inq) );
        for ( int i = 1; i <= n; ++i ) d[i] = INFt;
        d[0] = 0;
        q.push(0);
        while ( !q.empty() ) {
            int u = q.front(); q.pop();
            inq[u] = false;
            for ( int i = head[u]; i != -1; i = e[i].next ) {
                int fl = e[i].flow, ca = e[i].cap, v = e[i].to;
                long long w = e[i].w;
                if ( ca > fl && d[v] > d[u] + w ) {
                    d[v] = d[u] + w;
                    p[v] = u;
                    r[v] = i;
                    if ( !inq[v] ) {
                        inq[v] = true;
                        q.push(v);
                    }
                }
            }
        }
        if ( d[n] == INFt ) break;
        int a = INF;
        for ( int u = n; u != 0; u = p[u] ) {
            int ei = r[u];
            a = min( a, e[ei].cap - e[ei].flow );
        }
        for ( int u = n; u != 0; u = p[u] ) {
            int ei = r[u];
            e[ei].flow += a;
            e[ei^1].flow -= a;
        }
        ans += d[n] * a;
        maxf += a;
    }
}

int main()
{
    while ( scanf("%d%d", &n, &m) != EOF ) {
        init();
        mincost();
        if ( maxf < D ) printf("Impossible.\n");
        else printf("%lld\n", ans);
    }
    return 0;
}


你可能感兴趣的:(UVa10594 Data Flow(最小费用 最大流))