本题可以把求解的目标转换成从1到N两条不相交的路径,回想上一题,通过拆点来限制一边只能过一次,capacity为1,cost为-1来跑最大费用流,注意1点和N点的capacity要为2,因为需要过2次,答案就是最大费用流-2,本题的收获是输出路径,从每个点的出点出发(虚点)枚举其连接的下一个入点(实点),然后输出该入点,再dfs出点,如果只有一条边但有从1到N的边,也能输出答案,要考虑edge case
#include<bits/stdc++.h> using namespace std; #define lowbit(x) ((x)&(-x)) typedef long long LL; const int maxm = 1e5+5; const int INF = 0x3f3f3f3f; struct edge{ int u, v, cap, flow, cost, nex; } edges[maxm]; int head[maxm], cur[maxm], cnt, fa[maxm], d[maxm]; bool inq[maxm], vis[555]; map<string, int> cache; map<int, string> store; void init() { memset(head, -1, sizeof(head)); } void add(int u, int v, int cap, int cost) { edges[cnt] = edge{u, v, cap, 0, cost, head[u]}; head[u] = cnt++; } void addedge(int u, int v, int cap, int cost) { add(u, v, cap, cost), add(v, u, 0, -cost); } bool spfa(int s, int t, int &flow, LL &cost) { //for(int i = 0; i <= n+1; ++i) d[i] = INF; //init() memset(d, 63, sizeof(d)); memset(inq, false, sizeof(inq)); d[s] = 0, inq[s] = true; fa[s] = -1, cur[s] = INF; queue<int> q; q.push(s); while(!q.empty()) { int u = q.front(); q.pop(); inq[u] = false; for(int i = head[u]; i != -1; i = edges[i].nex) { edge& now = edges[i]; int v = now.v; if(now.cap > now.flow && d[v] > d[u] + now.cost) { d[v] = d[u] + now.cost; fa[v] = i; cur[v] = min(cur[u], now.cap - now.flow); if(!inq[v]) {q.push(v); inq[v] = true;} } } } if(d[t] == INF) return false; flow += cur[t]; cost += 1LL*d[t]*cur[t]; for(int u = t; u != s; u = edges[fa[u]].u) { edges[fa[u]].flow += cur[t]; edges[fa[u]^1].flow -= cur[t]; } return true; } int MincostMaxflow(int s, int t, LL &cost) { cost = 0; int flow = 0; while(spfa(s, t, flow, cost)); return flow; } void dfs1(int x, int N) { cout << store[x-N] << "\n"; vis[x] = true; for(int i = head[x]; i != -1; i = edges[i].nex) { int v = edges[i].v; if(edges[i].flow>0 && v <= N) { dfs1(v+N, N); return; } } } void dfs2(int x, int N) { vis[x] = true; for(int i = head[x]; i != -1; i = edges[i].nex) { int v = edges[i].v; if(edges[i].flow>0 && v <= N && !vis[v+N]) dfs2(v+N, N); } cout << store[x-N] << "\n"; } void run_case() { init(); int N, V; bool flag = false; string str; cin >> N >> V; for(int i = 1; i <= N; ++i) { cin >> str; cache[str] = i, store[i] = str; } for(int i = 0; i < V; ++i) { string t1, t2; cin >> t1 >> t2; int u = cache[t1], v = cache[t2]; if(u>v) swap(u, v); if(u == 1 && v == N) flag = true; addedge(u+N, v, 1, 0); } int s = 0, t = (N<<1)+2; addedge(s, 1, 2, 0), addedge(N<<1, t, 2, 0); for(int i = 1; i <= N; ++i) { if(i == 1 || i == N) addedge(i, i+N, 2, -1); else addedge(i, i+N, 1, -1); } LL cost = 0; int ans = MincostMaxflow(s, t, cost); if(ans == 2) { cout << -2-cost << "\n"; dfs1(1+N,N), dfs2(1+N,N); } else if(ans == 1 && flag) { cout << "2\n"; cout << store[1] << "\n" << store[N] << "\n" << store[1] << "\n"; } else { cout << "No Solution!\n"; } } int main() { ios::sync_with_stdio(false), cin.tie(0); run_case(); cout.flush(); return 0; }
来源:https://www.cnblogs.com/GRedComeT/p/12301309.html