Cow and Fields(最短路思维)

63 篇文章 1 订阅
18 篇文章 0 订阅

题意:
在这里插入图片描述
思路:
首先说一些性质,比如我们操作a,b点,如果a,b不在1~n的最短路径上,那么对答案是没有贡献的。如果在1到n的最短路径上呢?也就是我们要求Max(dist[a]+dist2[b]+1),dist1代表从1开始bfs,dist2代表从n开始bfs最短路径,O(n^2)枚举肯定不好,我们可以按照dist[a]-dist2[a]排序一下,然后这个答案就可以O(N)枚举得到了,我们在枚举的时候记录一下最大的dist[x],当前的dist2[b]已经固定了,更新一下答案就好了,最后注意要和原本图的最短路取一个min。

// Problem: 最大化最短路
// Contest: AcWing
// URL: https://www.acwing.com/problem/content/3800/
// Memory Limit: 256 MB
// Time Limit: 1000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

#include<bits/stdc++.h>
#define IL inline
#define x first
#define y second
typedef long long ll;
using namespace std;
const int N=400010;
int h[N],ne[N],idx,e[N];
void add(int a,int b)
{
	e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}
int dist1[N];
int dist2[N];
int a[N];int n,m,k;
void bfs(int s,int dist[])
{
	memset(dist,0x3f,4*N);
	queue<int>q;
	q.push(s);
	dist[s]=0;
	// cout<<s<<endl;
	while(q.size())
	{
		auto t=q.front();
		q.pop();
		for(int i=h[t];~i;i=ne[i])
		{
			int j=e[i];
			// cout<<t<<" "<<j<<endl;
			if(dist[j]>dist[t]+1)
			{
				dist[j]=dist[t]+1;
				q.push(j);
				
			}
		}
	}
}
int main()
{
	memset(h,-1,sizeof h);
	
	cin>>n>>m>>k;
	for(int i=1;i<=k;i++)	cin>>a[i];
	while(m--)
	{
		int a,b;
		cin>>a>>b;
		add(a,b);
		add(b,a);
	}
	bfs(1,dist1);
	bfs(n,dist2);
	// for(int i=1;i<=n;i++)	cout<<dist1[i]<<" ";
	// cout<<endl;
	int res=dist1[n];
	// for(int i=1;i<=k;i++)
		sort(a+1,a+1+k,[&](int a,int b)
		{
			return dist1[a]-dist2[a]<dist1[b]-dist2[b];
		});
	int ans=0;
	int mx=0;
	for(int i=1;i<=k;i++)
	{
		if(i>1)
		ans=max(ans,mx+dist2[a[i]]+1);
		mx=max(mx,dist1[a[i]]);
	}
	// cout<<res<<endl;
	// cout<<ans<<endl;
	cout<<min(ans,res)<<endl;
    return 0;
}





  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值