Solution

题目大意:给定一个无向图,求 1-n-1 来回的最短路径,每条边只能走一次。
用费用流求解一个流量为 2 的流就可以了。

Code

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
const int N = 20000;
const int M = 200000;
int n, m;
int head[N], nex[M], to[M], c[M], w[M], ce = 1;
void add(int u, int v, int cc, int ww) {
    to[++ce] = v; nex[ce] = head[u]; head[u] = ce; c[ce] = cc; w[ce] = ww;
    to[++ce] = u; nex[ce] = head[v]; head[v] = ce; c[ce] = 0; w[ce] = -ww;
}
queue<int> q;
int d[N], from[N], flow[N], edge[N];
int spfa(int s, int t) {
    memset(d, 0x3f, sizeof d);
    memset(flow, 0x3f, sizeof flow);
    memset(from, 0, sizeof from);
    memset(edge, 0, sizeof edge);
    d[s] = 0; q.push(s);
    while(!q.empty()) {
        int u = q.front(); q.pop();
        for(int i=head[u]; i; i=nex[i]) {
            int v = to[i];
            if(c[i] && d[u] + w[i] < d[v]) {
                d[v] = d[u] + w[i];
                from[v] = u; edge[v] = i;
                flow[v] = min(c[i], flow[u]);
                q.push(v);
            }
        }
    }
    int x = t;
    do {
        c[edge[x]] -= flow[t];
        c[edge[x]^1] += flow[t];
        x = from[x];
    } while(from[x]);
    return d[t];
}
int main() {
    scanf("%d%d", &n, &m);
    for(int i=1; i<=m; i++) {
        int u, v, w; scanf("%d%d%d", &u, &v, &w);
        add(u, v, 1, w);
        add(v, u, 1, w);
    }
    printf("%d\n", spfa(1, n) + spfa(1, n));
    return 0;
}

Description

When FJ's friends visit him on the farm, he likes to show them around. His farm comprises N (1 <= N <= 1000) fields numbered 1..N, the first of which contains his house and the Nth of which contains the big barn. A total M (1 <= M <= 10000) paths that connect the fields in various ways. Each path connects two different fields and has a nonzero length smaller than 35,000.

To show off his farm in the best way, he walks a tour that starts at his house, potentially travels through some fields, and ends at the barn. Later, he returns (potentially through some fields) back to his house again.

He wants his tour to be as short as possible, however he doesn't want to walk on any given path more than once. Calculate the shortest tour possible. FJ is sure that some tour exists for any given farm.

Input

  • Line 1: Two space-separated integers: N and M.
  • Lines 2..M+1: Three space-separated integers that define a path: The starting field, the end field, and the path's length.

Output

A single line containing the length of the shortest tour.

Sample Input

4 5
1 2 1
2 3 1
3 4 1
1 3 2
2 4 2

Sample Output

6