uva 10594 Data Flow (最小费最大流+题目给的数据有错)


uva 10594 Data Flow

题目大意:给出一张图,以及D, K,D代表所要传送的数据量,K代表每条边可以传送的数据量(就是容量),问在可以传送所有数据的前提下,最小耗费时间。

解题思路:建一个超级源点连向源点1,容量为D,然后求该图的最小费最大流。最后将求出的最大流与D比较,比D小输出inpossible,否则输出最小费。

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <queue>
using namespace std;
typedef long long ll;
const int N = 5005;
const ll INF = 1e18;
int n, m, s, t;
ll K, D;
struct Rec{
    ll u, v, cos;
}rec[N];
int pre[N], inq[N]; 
ll a[N], d[N];
struct Edge{
    int from, to;
    ll cap, flow;
    ll cos;
};

vector<Edge> edges;
vector<int> G[N];

void init() {
    for (int i = 0; i < N; i++) G[i].clear();
    edges.clear();
}

void addEdge(int from, int to, ll cap, ll flow, ll cos) {
    edges.push_back((Edge){from, to, cap, 0, cos});
    edges.push_back((Edge){to, from, 0, 0, -cos});
    int m = edges.size();
    G[from].push_back(m - 2);
    G[to].push_back(m - 1);
}
void input() {
    for (int i = 0; i < m; i++) {
        scanf("%lld %lld %lld", &rec[i].u, &rec[i].v, &rec[i].cos); 
    }
    scanf("%lld %lld", &D, &K);
    for (int i = 0; i < m; i++) {
        addEdge(rec[i].u, rec[i].v, K, 0, rec[i].cos);      
        addEdge(rec[i].v, rec[i].u, K, 0, rec[i].cos);
    }
    addEdge(0, 1, D, 0, 0);
}
int BF(int s, int t, ll& flow, ll& cost) {
    queue<int> Q;
    memset(inq, 0, sizeof(inq));
    memset(a, 0, sizeof(a));
    memset(pre, 0, sizeof(pre));
    for (int i = 0; i <= N; i++) d[i] = INF;
    d[s] = 0;
    a[s] = INF;
    inq[s] = 1;
    int flag = 1;
    pre[s] = 0;
    Q.push(s);
    while (!Q.empty()) {
        int u = Q.front(); Q.pop();
        inq[u] = 0;
        for (int i = 0; i < G[u].size(); i++) {
            Edge &e = edges[G[u][i]];
            if (e.cap > e.flow && d[e.to] > d[u] + e.cos) {
                d[e.to] = d[u] + e.cos;
                a[e.to] = min(a[u], e.cap - e.flow);
                pre[e.to] = G[u][i];
                if (!inq[e.to]) {
                    inq[e.to] = 1;
                    Q.push(e.to);
                }
            }   
        }
        flag = 0;
    }
    if (d[t] == INF) return 0;
    flow += a[t];
    cost += (ll)d[t] * (ll)a[t];
    for (int u = t; u != s; u = edges[pre[u]].from) {
        edges[pre[u]].flow += a[t];
        edges[pre[u]^1].flow -= a[t];
    }
    return 1;
}

int MCMF(int s, int t, ll& cost) {
    ll flow = 0;
    cost = 0;       
    while (BF(s, t, flow, cost));
    return flow;
}
int main() {
    while (scanf("%d %d", &n, &m) == 2) {
        init();
        input();    
        s = 0, t = n;
        ll cost;
        int ans = MCMF(s, t, cost);
        if (ans < D) printf("Impossible.\n");
        else printf("%lld\n", cost);
    }   
    return 0;
}
智能推荐

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告