上图时建边详解。
打印路径就是,反向边有流时就打印即可。细节见代码。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN = 5001;
const int MAXM = 50001;
struct MCMF
{
int n, s, t, cnt = 1;
long long maxflow=0, mincost=0;
int dis[MAXN], head[MAXN], incf[MAXN], pre[MAXN];//dis表示最短路,incf表示当前增广路上最小流量,pre表示前驱
bool vis[MAXN];
struct EDGE {
int nxt, to, cost, flow;
}ee[MAXM << 1];
inline void AD(int from, int to, int flow, int cost) {
ee[++cnt].nxt = head[from];
ee[cnt].to = to;
ee[cnt].cost = cost;
ee[cnt].flow = flow;
head[from] = cnt;
}
inline void add(int x, int y, int flow, int cost){
AD(x,y,flow,cost);AD(y,x,0,-cost);
//双向边
}
inline bool spfa()
{
queue <int> q;
for(int i=1;i<=n;i++)dis[i]=0x3f3f3f3f,vis[i]=0;
q.push(s);
dis[s] = 0;vis[s] = 1;
incf[s] = 1 << 30;
while(!q.empty()) {
int u = q.front();
vis[u] = 0;
q.pop();
for(register int i = head[u]; i; i = ee[i].nxt) {
if(!ee[i].flow) continue;//没有剩余流量
int v = ee[i].to;
if(dis[v] > dis[u] + ee[i].cost) {
dis[v] = dis[u] + ee[i].cost;
incf[v] = min(incf[u], ee[i].flow);//更新incf
pre[v] = i;
if(!vis[v]) vis[v] = 1, q.push(v);
}
}
}
if(dis[t] == 0x3f3f3f3f) return 0;
return 1;
}
void gao()
{
while(spfa()) {//如果有增广路
int x = t;
maxflow += incf[t];
mincost += (long long)dis[t] * incf[t];
int i;
while(x != s) {//遍历这条增广路,正向边减流反向边加流
i = pre[x];
ee[i].flow -= incf[t];
ee[i^1].flow += incf[t];
x = ee[i^1].to;
}
}
}
//先初始化
void init(int nn,int S,int T)
{
n=nn,s=S,t=T;
cnt=1;
for(int i=0;i<=n;i++)head[i]=0;
mincost=maxflow=0;
}
}mc;
map<string,int>mp;
map<int,string>sp;
int main()
{
int n,m;
cin>>n>>m;
string s,s2;
for(int i=1;i<=n;i++){
cin>>s;
mp[s]=i;
sp[i]=s;
}
int S=2*n+1,T=2*n+2;
mc.init(n*2+2,S,T);
mc.add(S,n+1,2,0);
mc.add(n,T,2,0);
for(int i=2;i<n;i++)mc.add(i+n,i,1,-1);
mc.add(1+n,1,2,-1);
if(n>1)mc.add(n+n,n,2,-1);
int inf=0x3f3f3f3f;
for(int i=1;i<=m;i++){
cin>>s>>s2;
int u=mp[s],v=mp[s2];
if(u>v)swap(u,v);
mc.add(u,v+n,inf,0);
}
mc.gao();
if(mc.maxflow!=2){
cout<<"No Solution!"<<endl;
return 0;
}
cout<<-mc.mincost -2<<endl;//返回起点
int p=n+1;
// cout<<sp[1]<<endl;
while(p!=n){
for(int i=mc.head[p];i;i=mc.ee[i].nxt){
int y=mc.ee[i].to,flow=mc.ee[i].flow,cost=mc.ee[i].cost;
if(i&1||!mc.ee[i^1].flow)continue;//不是最大流的边,或者不是正向边
// cout<<i<<" "<<p<<" - > "<<y<<" "<<flow<<" "<<cost<<endl;
mc.ee[i^1].flow--;
if(y<=n)cout<<sp[y]<<endl;
p=y;
break;
}
}
vector<int>pr;
p=n+1;
while(p!=n){
for(int i=mc.head[p];i;i=mc.ee[i].nxt){
int y=mc.ee[i].to,flow=mc.ee[i].flow,cost=mc.ee[i].cost;
if(i&1||!mc.ee[i^1].flow)continue;//不是最大流的边,或者不是正向边
// cout<<i<<" "<<p<<" - > "<<y<<" "<<flow<<" "<<cost<<endl;
mc.ee[i^1].flow--;
if(p<=n)pr.push_back(p);
//cout<<" -- "<<y<<endl;;
//cout<<mp[y]<<endl;
p=y;
break;
}
}
for(int i=pr.size()-1;i>=0;i--){
//cout<<i<<" "<<pr[i]<<" - > ";
cout<<sp[pr[i]]<<endl;
}
return 0;
}
/*
3 3
a b c
a b
b c
a c
*/