首页 > 代码库 > uva10806

uva10806

题目链接请戳 这里

 

解题思路

可以用最小费用最大流建模。

每条道路上的时间为费用,容量为1表示只能一个人通过(因为只对道路做了限值,顶点可以重复通过)

另建标号为0的顶点,其到标号为1的顶点容量为2,花费为0。

 

代码

#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;

const int maxn = 110;
const int maxm = 5010;
const int INF = 1000000000;

//这里用的是lrj紫书里的模板
struct Edge {
    int from, to, cap, flow, cost;
    Edge(int u, int v, int c, int f, int w):from(u), to(v), cap(c), flow(f), cost(w) {}
};

struct MCMF {
    int n, m;
    vector<Edge> edges;
    vector<int> G[maxn];
    int inq[maxn];
    int d[maxn];
    int p[maxn];
    int a[maxn];
    
    void init(int n)
    {
        this->n = n;
        for (int i = 0; i <= n; i++) G[i].clear();
        edges.clear();
    }
    
    void AddEdge(int from, int to, int cap, int cost) {
        edges.push_back(Edge(from, to, cap, 0, cost));
        edges.push_back(Edge(to, from, 0, 0, -cost));
        m = edges.size();
        G[from].push_back(m - 2);
        G[to].push_back(m - 1);
    }
    
    bool BellmanFord(int s, int t, int &flow, long long &cost) {
        for (int i = 0; i <= n; i++) d[i] = INF;
        memset(inq, 0, sizeof(inq));
        d[s] = 0; inq[s] = 1; p[s] = -1; a[s] = INF;
        
        queue<int> Q;
        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.cost) {
                    d[e.to] = d[u] + e.cost;
                    p[e.to] = G[u][i];
                    a[e.to] = min(a[u], e.cap - e.flow);
                    if (!inq[e.to]) { Q.push(e.to); inq[e.to] = 1; }
                }
            }
        }
        if (d[t] == INF) return false;
        flow += a[t];
        cost += (long long)d[t] * (long long)a[t];
        for (int u = t; u != s; u = edges[p[u]].from) {
            edges[p[u]].flow += a[t];
            edges[p[u] ^ 1].flow -= a[t];
        }
        return true;
    }
    
    int MincostMaxflow(int s, int t, long long &cost) {
        int flow = 0; cost = 0;
        while (BellmanFord(s, t, flow, cost));
        return flow;
    }
};

int from[maxm], to[maxm];
int w[maxm];

int main()
{
    int n, m;
    MCMF A;
    scanf("%d", &n);
    while (n != 0) {
        scanf("%d", &m);
        long long cost = 0;
        A.init(n);
        //建立标号为0的顶点
        A.AddEdge(0, 1, 2, 0);
        //因为为无向图,所以要建来回两条边
        for (int i = 0; i < m; i++) {
            scanf("%d%d%d", &from[i], &to[i], &w[i]);
            A.AddEdge(from[i], to[i], 1, w[i]);
            A.AddEdge(to[i], from[i], 1, w[i]);
        }
        int f;
        f = A.MincostMaxflow(0, n, cost);
        if (f != 2) printf("Back to jail\n");
        else printf("%lld\n", cost);
        scanf("%d", &n);
    }
    return 0;
}

 

uva10806