• 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));
    }
    
  • 相关阅读:
    苹果一体机发射Wi-Fi
    iphone 屏蔽系统自动更新,消除设置上的小红点
    data parameter is nil 异常处理
    copy与mutableCopy的区别总结
    java axis2 webservice
    mysql 远程 ip访问
    mysql 存储过程小问题
    mysql游标错误
    is not writable or has an invalid setter method错误的解决
    Struts2中关于"There is no Action mapped for namespace / and action name"的总结
  • 原文地址:https://www.cnblogs.com/Tuesdayzz/p/5758770.html
Copyright © 2020-2023  润新知