【网络流24题】航空路线问题 题解

题目传送门

题目大意: 给出一张图,点 1 1 1 n n n 自西向东排列, 1 1 1 在最西端, n n n 在最东端,找到一条经过点数最多的不经过重复点的路径(除了点 1 1 1),且这条路径分两段,第一段从 1 1 1 走到 n n n,并且只能向东走,第二段从 n n n 走回 1 1 1,且只能向西走。

题解

其实等于从 1 1 1 走到点 n n n 走两次。

由于每个点只能走一次,很容易想到拆点(下面称拆出来的两个点为出点和入点),然后中间连一条流量为 1 1 1 的边,由于要求点数最大,所以这条边上再加一个 1 1 1 的费用。对于其他的边 ( x , y ) (x,y) (x,y),连一条由 x x x 的出点到 y y y 的入点的边,流量为 1 1 1,费用为 0 0 0。然后跑一次最大费用流即可。

还要特判一下,如果最大流量是 1 1 1,一般情况下就无解了,但是如果存在一条边 ( 1 , n ) (1,n) (1,n),那么答案就是 1 → n → 1 1\to n\to 1 1n1

代码如下:

#include <cstdio>
#include <cstring>
#include <string>
#include <map>
#include <iostream>
#include <algorithm>
using namespace std;
#define maxn 210
#define inf 1e9

int n,m,ans=0;
string a[maxn];
map<string,int> Map;
struct edge{int x,y,z,cost,next;};
edge e[maxn*maxn<<1];
int first[maxn],len=1;
void buildroad(int x,int y,int z,int cost)
{
	e[++len]=(edge){x,y,z,cost,first[x]};
	first[x]=len;
}
bool first_to_n=false;
int f[maxn],fa[maxn],q[maxn],st,ed;
bool v[maxn];
bool SPFA(int T)
{
	memset(f,0,sizeof(f));
	st=1,ed=2;q[st]=1;v[1]=true;
	while(st!=ed)
	{
		int x=q[st++];st=st>2*n?1:st;
		for(int i=first[x];i;i=e[i].next)
		{
			int y=e[i].y;
			if(e[i].z&&f[y]<f[x]+e[i].cost)
			{
				f[y]=f[x]+e[i].cost;fa[y]=i;
				if(!v[y])v[q[ed++]=y]=true,ed=ed>2*n?1:ed;
			}
		}
		v[x]=false;
	}
	return f[T];
}
inline void boom(){printf("No Solution!");}
void go1(int x)
{
	v[x]=true;cout<<a[x]<<endl;
	if(x==n)return;
	for(int i=first[x+n];i;i=e[i].next)
	if(!e[i].z&&!v[e[i].y]){go1(e[i].y);break;}
}
void go2(int x)
{
	v[x]=true;
	if(x==n)return;
	for(int i=first[x+n];i;i=e[i].next)
	if(!e[i].z&&!v[e[i].y]){go2(e[i].y);break;}
	cout<<a[x]<<endl;
}

int main()
{
	cin>>n>>m;
	for(int i=1;i<=n;i++)
	cin>>a[i],Map[a[i]]=i,
	buildroad(i,i+n,(i!=1?1:inf),1),buildroad(i+n,i,0,-1);
	for(int i=1,x,y;i<=m;i++)
	{
		cin>>a[0];x=Map[a[0]];
		cin>>a[0];y=Map[a[0]];
		if(x>y)swap(x,y);
		first_to_n|=(x==1&&y==n);
		buildroad(x+n,y,1,0),buildroad(y,x+n,0,0);
	}
	if(SPFA(2*n))
	{
		for(int i=fa[2*n];i;i=fa[e[i].x])
		e[i].z--,e[i^1].z++,ans+=e[i].cost;
		if(SPFA(n))
		{
			for(int i=fa[n];i;i=fa[e[i].x])
			e[i].z--,e[i^1].z++,ans+=e[i].cost;
			printf("%d\n",ans-1);
			go1(1);go2(1);
		}
		else if(first_to_n)cout<<2<<endl<<a[1]<<endl<<a[n]<<endl<<a[1];
		else boom();
	}
	else boom();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值