zoukankan      html  css  js  c++  java
  • POJ 2135_Farm Tour

    题意:

    从出发点到目的地往返一次,道路i连接着ai号和bi号,长度为ci。同一条路只能走一次,求最小路径长度。

    分析:

    如果没有往返,那么就是简单的最短路问题。如果规定严格从左到右,那么就是简单的双调旅行商问题。对于本题,同样还是将往返看成是从出发地开始的两条没有公共边的路径,便可以转化为求流量为2的最小费用流了~注意边为无向边

    代码:

    #include<cstdio>
    #include<vector>
    #include<iostream>
    #include<queue>
    using namespace std;
    #define se second
    #define fi first
    typedef pair<int, int>pii;//first 顶点距离,secon顶点编号
    struct edge{int to, cap, cost, rev;};
    const int maxn = 20005, INF =0x3fffffff;
    int V, s, t;
    vector<edge>G[maxn];
    int dist[maxn], prevv[maxn], preve[maxn], h[maxn];//h记录顶点的势
    void add_edge(int from, int to, int cap, int cost)
    {
        G[from].push_back((edge){to, cap, cost, G[to].size()});
        G[to].push_back((edge){from, 0, -cost, G[from].size() - 1});
    }
    int min_cost_flow(int s, int f)
    {
        int res = 0;
        fill(h, h + V + 1, 0);
        while(f > 0){
            priority_queue<pii, vector<pii>, greater<pii> >que;
            fill(dist, dist + V + 1, INF);
            dist[s] = 0;
            que.push(pii(0, s));
            while(!que.empty()){
                pii p = que.top();que.pop();
                int v = p.se;
                if(dist[v] < p.fi) continue;
                for(int i = 0; i < G[v].size(); i++){
                    edge &e = G[v][i];
                    if(e.cap>0&&dist[e.to]>dist[v] + e.cost + h[v] - h[e.to]){
                        dist[e.to] = dist[v] + e.cost + h[v] - h[e.to];
                        prevv[e.to] = v; preve[e.to] = i;
                        que.push(pii(dist[e.to], e.to));
                    }
                }
            }
            if(dist[t] == INF) return -1;
            for(int i = 1; i <= V; i++) h[i] +=dist[i];
            int d = f;
            for(int v = t; v != s; v = prevv[v]){
                d = min(d, G[prevv[v]][preve[v]].cap);
            }
            f -= d;
            res += d * h[t];
            for(int v = t; v!= s; v = prevv[v]){
                edge &e = G[prevv[v]][preve[v]];
                e.cap -= d;
                G[v][e.rev].cap += d;
            }
        }
        return res;
    }
    int main (void)
    {
        int m;scanf("%d%d",&V, &m);
        int a, b, c;
        for(int i = 0; i < m; i++){
            scanf("%d%d%d",&a, &b, &c);
            add_edge(a, b, 1, c);
            add_edge(b, a, 1, c);
        }
        s = 1, t = V;
        printf("%d
    ",min_cost_flow(s,2));
    }
    
  • 相关阅读:
    Connected Components? Codeforces
    洛谷 P1344 [USACO4.4]追查坏牛奶Pollutant Control
    洛谷 P4174 [NOI2006]最大获利 && 洛谷 P2762 太空飞行计划问题 (最大权闭合子图 && 最小割输出任意一组方案)
    表达式求值
    费用流(自用,勿看)
    二分图??(自用,勿看)
    C 标准库
    Linux-socket使用
    C 标准库
    C 标准库
  • 原文地址:https://www.cnblogs.com/Tuesdayzz/p/5758770.html
Copyright © 2011-2022 走看看