# 【網絡流24題-洛谷-P2770】航空路線問題（最長不相交路徑、最小費用最大流）

## 題目描述

(1)從最西端城市出發，單向從西向東途經若干城市到達最東端城市，然後再單向從東向西飛回起點(可途經若干城市)。

(2)除起點城市外，任何城市只能訪問 1 次。

## 輸入輸出樣例

``````8 9
Vancouver
Yellowknife
Edmonton
Calgary
Winnipeg
Toronto
Montreal
Halifax
Vancouver Edmonton
Vancouver Calgary
Calgary Winnipeg
Winnipeg Toronto
Toronto Halifax
Montreal Halifax
Edmonton Montreal
Edmonton Yellowknife
Edmonton Calgary``````

``````7
Vancouver
Edmonton
Montreal
Halifax
Toronto
Winnipeg
Calgary
Vancouver ``````

## 說明/提示

``````#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<string>
#include<vector>
#include<unordered_map>
#define mod (1000000007)
using namespace std;
typedef long long ll;
const int MAX = 2e5 + 5;
const int inf = 0x3f3f3f3f;
struct node {
int v,f,w,nxt;
} e[50005<<2];
int n,m,N;
int r[MAX];
void add(int u,int v,int f,int cost=0) {
e[++tot].v = u;e[tot].f = 0; e[tot].w = -cost;e[tot].nxt = head[v];head[v] = tot;
}
bool bfs(int s,int t) {
for(int i = 0; i<=N; i++) d[i]=inf,vis[i]=0;
d[s]=0;
queue<int>q;
q.push(s);
while(!q.empty()) {
int u=q.front();
q.pop();
vis[u]=0;
int j=e[i].v;
if(e[i].f&&d[j]>d[u]+e[i].w) {
d[j]=d[u]+e[i].w;
p[j]=i;
if(!vis[j])vis[j]=1,q.push(j);
}
}
}
return d[t]<inf;
}
ll MCMF(int s,int t,ll &flow) {
ll ans=0;
while(bfs(s,t)) {
int x=t,f=inf;
while(x!=s) {
f = min(f,e[p[x]].f),x=e[p[x]^1].v;
}
flow += f;
ans+=1LL*d[t]*f;
x=t;
while(x!=s) {
e[p[x]].f-=f,e[p[x]^1].f+=f;
x=e[p[x]^1].v;
}
}
return ans;
}
unordered_map<string,int> mp;
unordered_map<int,string> name;
void bfs2(int st,int &ct,int a[]){
queue<int> q;
q.push(st);
while(!q.empty()){
int nn=q.front();q.pop();
a[ct++]=nn;
if(e[i].f==0&&i<(i^1))//反向邊
q.push(e[i].v);
}
}
}
char s[1000],ss[1000];
int ans[1000],ans2[1000];
int main() {
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++){
scanf("%s",s);
mp[s]=i;name[i]=s;
if(i!=n&&i!=1)
}
int st=1,ed=n+n,ff=0;N=ed;
for(int i=1;i<=m;i++){
scanf("%s%s",s,ss);
int t1=mp[s];
int t2=mp[ss];
if(t1>t2) swap(t1,t2);
if(t1==1&&t2==n)ff=1;
}
ll fl=0,an=0;
an=MCMF(st,ed,fl);
if(fl<1)puts("No Solution!");
else if(fl==1){
if(ff){//如果起點到終點有直接的路徑，即使只有1條也是滿足條件的
cout<<2<<endl;
cout<<name[1]<<endl;
cout<<name[n]<<endl;
cout<<name[1]<<endl;
}
else puts("No Solution!");
}
else{
printf("%lld\n",-an-2);
queue<int> q;
if(e[i].f==0){
q.push(e[i].v);
}
}
int tp1=1,tp2=1;
ans[0]=1;
ans2[0]=1;
bfs2(q.front(),tp1,ans);q.pop();
bfs2(q.front(),tp2,ans2);q.pop();
for(int i=0;i<tp1;i++)
if(ans[i]<=n) //printf("%d\n",ans[i]);
cout<<name[ans[i]]<<endl;
for(int i=tp2-1;i>=0;i--)
if(ans2[i]<n) //printf("%d\n",ans2[i]);
cout<<name[ans2[i]]<<endl;
}
return 0 ;
}``````