CodeForces-1307D Cow and Fields BFS Seeking Distance + Thinking

CodeForces - 1307D Cow and Fields

Original title address:

http://codeforces.com/contest/1307/problem/D

Topic:
For an undirected graph, and a series of points, you can choose any two of these points and connect an edge to make the shortest path of 1 —> n the largest. Ask what is the largest shortest path.

Basic idea:
First find the shortest path from 1 to these points by bfs twice, and record it in the array dis1; the shortest path from n to these points, record it in the array dis2;
then if the pair of edges 1-> n is the shortest The road has an effect, that is, the maximum shortest path after connecting the edges is greater than the original shortest path, then the answer is the maximum shortest path after connecting the edges, otherwise the original shortest path is taken.
We consider how to find the maximum shortest path after connecting edges, the maximum shortest path is max (min (dis1 [a] + dis2 [b] +1, dis1 [b] + dis2 [a] + 1)) (a, b is Any two of those points given earlier), we might as well assume dis1 [a] + dis2 [b] <= dis2 [b] + dis1 [a], then we only need to find dis1 [a] + dis2 [b] The maximum value of the shift inequality is dis1 [a]-dis2 [a] <= dis1 [b]-dis2 [b] According to this order, we enumerate the largest dis1 [a] updated each time, and update at the same time The answer is dis1 [a] + dis2 [b] + 1.
Finally, remember to compare with the original shortest path.

Implementation code:

#include <bits/stdc++.h>
using namespace std;
#define IO std::ios::sync_with_stdio(false)
#define int long long
#define INF 0x3f3f3f3f

const int maxn = 2e5+10;
int n,m,k;
int a[maxn];
int dis1[maxn],dis2[maxn];
vector<int> G[maxn];
void bfs(int *dis,int s) {
    fill(dis, dis + n + 1, INF);
    queue<int> q;
    q.push(s);
    dis[s] = 0;
    while (!q.empty()) {
        int v = q.front();
        q.pop();
        for (auto it : G[v]) {
            if (dis[it] == INF) {
                dis[it] = dis[v] + 1;
                q.push(it);
            }
        }
    }
}
struct Node {
    int x, y;

    Node(int _x, int _y) { x = _x, y = _y; }

    bool operator<(const Node &no) const {
        return x < no.x;
    }
};
vector<Node> memo;
signed main() {
    IO;
    cin >> n >> m >> k;
    for (int i = 0; i < k; i++) cin >> a[i];
    for (int i = 0; i < m; i++) {
        int u, v;
        cin >> u >> v;
        G[u].push_back(v);
        G[v].push_back(u);
    }
    bfs(dis1, 1);
    bfs(dis2, n);
    for (int i = 0; i < k; i++) memo.emplace_back(Node(dis1[a[i]] - dis2[a[i]], a[i]));
    sort(memo.begin(), memo.end());
    int ans = 0;
    int mx = -INF;
    for (auto it : memo) {
        ans = max(ans, mx + dis2[it.y] + 1);
        mx = max(mx, dis1[it.y]);
    }
    ans = min(ans, dis1[n]);
    cout << ans << endl;
    return 0;
}
Published 23 original articles · praised 7 · visits 1753

Guess you like

Origin blog.csdn.net/weixin_44164153/article/details/104400155