1307D - Cow and Fields(思维+最短路)

https://codeforces.com/problemset/problem/1307/D


 

1 ,n(不走这条边,即dis1[ n ])
1,x,y,n(dis1[ x ] + 1 + disn[ y ]
1,y,x,n(dis1[ y ] + 1 + disn[ x ])

做两次bfs求出dis1disn,

此时n^2暴力。

优化:对v排序。

假如为1->i->j->n,那么满足dis1[i]+disn[j]<dis1[j]+disn[i],移项得dis1[i]-disn[i]<dis1[j]-disn[j],也就是说当dis1[i]-disn[i]小的时候,那么先到i这个点比先到j点更优,我们就可以根据这个排序k个。

此时只要枚举i,j的方案数了

对于j,维护一个后缀最大。

#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=2e5+1000;
typedef long long LL;
typedef pair<LL,LL>P;
inline LL read(){LL x=0,f=1;char ch=getchar();	while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;}
vector<LL>g[maxn];
bool vis[maxn];
LL cnt[maxn],dis1[maxn],disn[maxn];
struct DIS{
   LL dis1,disn;
}p[maxn];
bool cmp(DIS A,DIS B){
    return A.dis1-A.disn<B.dis1-B.disn;
}
LL sum[maxn];
void bfs(LL dis[],LL st){
    dis[st]=0;
    vis[st]=true;
    queue<P>que;
    que.push({st,0});
    while(!que.empty()){
        LL u=que.front().first;
        LL cost=que.front().second;que.pop();
        for(LL i=0;i<g[u].size();i++){
            LL v=g[u][i];
            if(vis[v]) continue;
            vis[v]=true;
            dis[v]=cost+1;
            que.push({v,dis[v]});
        }
    }
}
int main(void){
   cin.tie(0);std::ios::sync_with_stdio(false);
   LL n,m,k;cin>>n>>m>>k;
   for(LL i=1;i<=k;i++) cin>>cnt[i];
   for(LL i=1;i<=m;i++){
       LL u,v;cin>>u>>v;
       g[u].push_back(v);
       g[v].push_back(u);
   }
   bfs(dis1,1);
   memset(vis,0,sizeof(vis));
   bfs(disn,n);

//   for(LL i=1;i<=n;i++){
//      cout<<dis1[i]<<" ";
//   }
//   cout<<"\n";
//   for(LL i=1;i<=n;i++){
//      cout<<disn[i]<<" ";
//   }
//   cout<<"\n";
   ///dis1[i]+1+disn[j];
   ///dis1[j]+1+disn[i];
   LL ans=0;
   for(LL i=1;i<=k;i++){
      p[i].dis1=dis1[cnt[i]];
      p[i].disn=disn[cnt[i]];
   }
   sort(p+1,p+1+k,cmp);
//   for(LL i=1;i<=k;i++){
//     cout<<p[i].dis1<<" ";
//   }
//   cout<<"\n";
//   for(LL i=1;i<=k;i++){
//     cout<<p[i].disn<<" ";
//   }
//   cout<<"\n";
   for(LL i=k;i>=1;i--){
      sum[i]=max(sum[i+1],p[i].disn);
   }
//   for(LL i=1;i<=k;i++){
//      cout<<sum[i]<<" ";
//   }
//   cout<<"\n";
   for(LL i=1;i<k;i++){
      ans=max(ans,p[i].dis1+1+sum[i+1]);
   }
//   cout<<"ans="<<ans<<"\n";
//   cout<<disn[1]<<"\n";
   cout<<min(ans,disn[1])<<"\n";
   return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值