【題解】Codeforces 1307D. Cow and Fields

【題目敘述】http://codeforces.com/contest/1307/problem/D
【解題想法】BFS

#include <iostream>
#include <vector>
#include <queue>
#include <cstring>
#include <algorithm>
using namespace std;
 
int n, m, k, s[200005], t[200005], x, y;
vector <int> a;
vector <int> v[200005];
 
bool cmp(int x, int y){
    if (s[x]-t[x] != s[y]-t[y]) return s[x]-t[x] < s[y]-t[y];
    else return x < y;
}
 
int main() {
    cin >> n >> m >> k;
    for (int i = 0; i < k; i++){
        cin >> x;
        a.push_back(x);
    }
    for (int i = 0; i < m; i++){
        cin >> x >> y;
        v[x].push_back(y);
        v[y].push_back(x);
    }
    queue <int> q;
    memset(s, -1, sizeof(s));
    q.push(1);
    s[1] = 0;
    while (!q.empty()){
        x = q.front();
        q.pop();
        for (int i:v[x]){
            if(s[i] == -1){
                s[i] = s[x]+1;
                q.push(i);
            }
        }
    }
    memset(t, -1, sizeof(t));
    q.push(n);
    t[n] = 0;
    while (!q.empty()){
        x = q.front();
        q.pop();
        for (int i:v[x]){
            if(t[i] == -1){
                t[i] = t[x]+1;
                q.push(i);
            }
        }
    }
    sort(a.begin(), a.end(), cmp);
    int ans = 0, mx = s[a[0]];
    for (int i = 1; i < k; i++){
        ans = max(ans, mx+t[a[i]]+1);
        mx = max(mx, s[a[i]]);
    }
    ans = min(ans, s[n]);
    cout << ans << "\n";
}
分享本文 Share with friends