[CF1307D] Cow and Fields

给一张联通无向图,边权全 1,其中有 k 个关键点,求选取一对关键点增加一条边之后 1~n 的最短路的最大值

Solution

(1,n) 为起点 BFS 出最短路数组,分别记为 (a[],b[])

对特殊点的编号按照 (x_i) 升序排序,那么容易证明对于每个 (x_i),只需要考虑 (y_{i+1}) 即可

#include <bits/stdc++.h>
using namespace std;

const int N = 200005;
vector <int> g[N];
int n,m,k,a[N],x[N],y[N],v[N],t1,t2;

bool cmp(int p,int q) {
    return x[p]<x[q];
}

signed main() {
    ios::sync_with_stdio(false);
    cin>>n>>m>>k;
    for(int i=1;i<=k;i++) cin>>a[i];
    for(int i=1;i<=m;i++) {
        cin>>t1>>t2;
        g[t1].push_back(t2);
        g[t2].push_back(t1);
    }
    queue <int> qu;
    memset(x,0x3f,sizeof x);
    x[1]=0;
    qu.push(1);
    while(qu.size()) {
        int p=qu.front();
        qu.pop();
        for(int q:g[p]) {
            if(x[q]>x[p]+1) {
                x[q]=x[p]+1;
                if(v[q]==0) v[q]=1,qu.push(q);
            }
        }
    }
    memset(y,0x3f,sizeof x);
    memset(v,0,sizeof v);
    y[n]=0;
    qu.push(n);
    while(qu.size()) {
        int p=qu.front();
        qu.pop();
        for(int q:g[p]) {
            if(y[q]>y[p]+1) {
                y[q]=y[p]+1;
                if(v[q]==0) v[q]=1,qu.push(q);
            }
        }
    }
    sort(a+1,a+k+1,cmp);
    int s=0;
    for(int i=1;i<k;i++) {
        s=max(s,min(x[n],min(x[a[i]]+y[a[i+1]],y[a[i]]+x[a[i+1]])+1));
    }
    cout<<s;
}

原文地址:https://www.cnblogs.com/mollnn/p/12610655.html