题意:给定一个图,求1-n的两条不相交的路线,并且权值和最小。
析:最小费用流,把每个结点都拆成两个点,中间连一条容量为1的边,然后一个作为入点,另一个是出点。最后跑两次最小费用流就行了。
代码如下:
#pragma comment(linker, "/STACK:1024000000,1024000000") #include <cstdio> #include <string> #include <cstdlib> #include <cmath> #include <iostream> #include <cstring> #include <set> #include <queue> #include <algorithm> #include <vector> #include <map> #include <cctype> #include <cmath> #include <stack> #include <sstream> #define debug() puts("++++"); #define gcd(a, b) __gcd(a, b) #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 #define freopenr freopen("in.txt", "r", stdin) #define freopenw freopen("out.txt", "w", stdout) using namespace std; typedef long long LL; typedef unsigned long long ULL; typedef pair<int, int> P; const int INF = 0x3f3f3f3f; const double inf = 0x3f3f3f3f3f3f; const double PI = acos(-1.0); const double eps = 1e-5; const int maxn = 2000 + 10; const int mod = 1e6; const int dr[] = {-1, 0, 1, 0}; const int dc[] = {0, 1, 0, -1}; const char *de[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"}; int n, m; const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; inline bool is_in(int r, int c){ return r >= 0 && r < n && c >= 0 && c < m; } struct Edge{ int from, to, cap, flow; LL cost; }; struct MCMF{ int n, m; vector<Edge> edges; vector<int> G[maxn]; int inq[maxn]; LL 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, LL 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, LL &cost){ for(int i = 0; i < n; ++i) d[i] = INF; memset(inq, 0, sizeof inq); d[s] = 0; inq[s] = 1; p[s] = 0; 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 += d[t] * a[t]; int u = t; while(u != s){ edges[p[u]].flow += a[t]; edges[p[u]^1].flow -= a[t]; u = edges[p[u]].from; } return true; } LL minCost(int s, int t){ int flow = 0; LL cost = 0; while(BellmanFord(s, t, flow, cost)); return cost; } }; MCMF mcmf; int main(){ while(scanf("%d %d", &n, &m) == 2){ int u, v, val; mcmf.init(n+n+1); for(int i = 0; i < m; ++i){ scanf("%d %d %d", &u, &v, &val); mcmf.addEdge(u+n, v, 1, val); } for(int i = 2; i < n; ++i) mcmf.addEdge(i, i+n, 1, 0); mcmf.addEdge(1, 1+n, 2, 0); mcmf.addEdge(n, n+n, 2, 0); printf("%lld ", mcmf.minCost(1, n+n) + mcmf.minCost(1, n+n)); } return 0; }