Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 14270 | Accepted: 5441 |
Description
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
* Lines 2..M+1: Three space-separated integers that define a path: The starting field, the end field, and the path's length.
Output
Sample Input
4 5 1 2 1 2 3 1 3 4 1 1 3 2 2 4 2
Output
6
你从1到n点,再回到1的最小花费,
题意:#include<stdio.h>00 #include<iostream> #define min(a,b) ((a)<(b)?(a):(b)) using namespace std; const int nMax = 1050; const int eMax = 40050; const int inf = 99999999; struct{ int v, cap, cost, next, re; }edge[eMax]; int n, m, ans; int k, edgeHead[nMax]; int sta[nMax], pre[nMax], dis[nMax]; bool vis[nMax]; void addEdge(int u, int v, int ca, int co){ edge[k].v = v; edge[k].cap = ca; edge[k].cost = co; edge[k].next = edgeHead[u]; edge[k].re = k + 1; edgeHead[u] = k ++; edge[k].v = u; edge[k].cap = 0; edge[k].cost = -co; edge[k].next = edgeHead[v]; edge[k].re = k - 1; edgeHead[v] = k ++; } bool spfa(){ int i, top = 0; for(i = 0; i <= n; i ++){ dis[i] = inf; vis[i] = false; } dis[0] = 0; sta[++ top] = 0; vis[0] = true; while(top){ int u = sta[top --]; for(i = edgeHead[u]; i != 0; i = edge[i].next){ int v = edge[i].v; if(edge[i].cap && dis[v] > dis[u] + edge[i].cost){ dis[v] = dis[u] + edge[i].cost; pre[v] = i; if(!vis[v]){ vis[v] = true; sta[++ top] = v; } } } vis[u] = false; } if(dis[n] == inf) return false; return true; } void end(){ int u, p, sum = inf; for(u = n; u != 0; u = edge[edge[p].re].v){ p = pre[u]; sum = min(sum, edge[p].cap); } for(u = n; u != 0; u = edge[edge[p].re].v){ p = pre[u]; edge[p].cap -= sum; edge[edge[p].re].cap += sum; ans += sum * edge[p].cost; } } int main(){ k = 1; scanf("%d%d", &n, &m); while(m --){ int u, v, w; scanf("%d%d%d", &u, &v, &w); addEdge(u, v, 1, w); addEdge(v, u, 1, w); } addEdge(0, 1, 2, 0); addEdge(n, n+1, 2, 0); n ++; ans = 0; while(spfa()) end(); cout << ans << endl; return 0; }