https://www.luogu.org/problemnew/show/P2770
建图方法: s s s到 1 1 1容量为2,费用为0, n ′ n' n′到 t t t容量为2,费用为0, 1 − > 1 ′ 和 n − > n ′ 1->1'和n->n' 1−>1′和n−>n′容量为2,费用为-1,其余 x − > x ′ x->x' x−>x′容量为1,费用为-1,再连接航线即可。
#include
using namespace std;
const int maxn=100*2+100;
const int INF=0x3f3f3f3f;
typedef long long ll;
struct Edge{
int from,to,cap,flow,cost;
};
struct MCMF{
int n,m,s,t;
vector<Edge> edges;
vector<int> G[maxn];
int inq[maxn];
ll d[maxn];
int p[maxn];
int a[maxn];
map<string,int> city;
map<int,string> city2;
bool linked;
void init()
{
int m0;
string str,str2;
cin>>n>>m0;
s=0,t=1;
AddEdge(s,1*2,2,0);
AddEdge(n*2+1,t,2,0);
for(int i=1;i<=n;i++)
{
cin>>str;
city[str]=i;
city2[i]=str;
AddEdge(i*2,i*2+1,i==1||i==n?2:1,-1);
}
for(int i=1;i<=m0;i++)
{
cin>>str>>str2;
int from=city[str],to=city[str2];
if(from>to)swap(from,to);
if(from==1&&to==n)linked=1;
AddEdge(from*2+1,to*2,1,0);
}
}
void AddEdge(int from,int to,int cap,int 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& flow,int& cost)
{
for(int i=0;i<=2*n+1;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]==0){inq[e.to]=1;Q.push(e.to);}
}
}
}
if(d[t]==INF)return false;
flow+=a[t];
cost+=a[t]*d[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;
}
int Mincost()
{
int flow=0,cost=0;
while(BellmanFord(flow,cost));
if(flow!=2)
{
if(linked)
{
cout<<2<<"\n";
cout<<city2[1]<<"\n"<<city2[n]<<"\n"<<city2[1]<<"\n";
exit(0);
}
puts("No Solution!");
exit(0);
}
return cost;
}
void print(int cost)
{
cout<<cost<<endl;
int nxt[maxn]={0},nxt2[maxn]={0};
for(int i=0;i<m;i+=2)
{
int from=edges[i].from,to=edges[i].to,flow=edges[i].flow;
if(from==s||from==t||to==s||to==t||from/2==to/2||flow==0)continue;
if(!nxt[from/2])nxt[from/2]=to/2;
else nxt2[from/2]=to/2;
}
int u=1;
while(u!=n)
{
cout<<city2[u]<<"\n";
u=nxt[u];
}
stack<string> stk;
stk.push(city2[1]);
u=nxt2[1];
while(u)
{
stk.push(city2[u]);
u=nxt[u];
}
while(!stk.empty())cout<<stk.top()<<"\n",stk.pop();
}
}ans;
int main()
{
//freopen("input.in","r",stdin);
ans.init();
int cost=-ans.Mincost()-2;
ans.print(cost);
return 0;
}