L3-008 喊山

#include <bits/stdc++.h>

using namespace std;

using pii = pair<int, int>;

const int N = 10010;

vector<int> G[N];
bool st[N];
int dist[N];
int res = 1e9;
int d = -1;

void Dijkstra(int u) {
    memset(dist, 0x3f, sizeof dist);
    memset(st, 0, sizeof st);
    dist[u] = 0;
    priority_queue<pii, vector<pii>, greater<pii>> heap;
    heap.push({dist[u], u});

    while (heap.size()) {
        auto t = heap.top();
        heap.pop();

        int u = t.second;
        if (st[u]) continue;
        st[u] = true;

        for (auto v : G[u]) {
            if (dist[v] > dist[u] + 1) {
                dist[v] = dist[u] + 1;
                heap.push({dist[v], v});
            }
        }
    }
}

bool dfsst[N];

void dfs(int u) {
    dfsst[u] = true;
    for (auto v : G[u]) {
        if (dfsst[v]) continue;
        if (dist[v] > d) {
            res = v, d = dist[v];            
        } else if (dist[v] == d) {
            if (res > v) {
                res = v;
            }
        }
        dfs(v);
    }
}

int main() {
    int n, m, k;
    cin >> n >> m >> k;
    //cout << n << m << k << "\n";
    for (int i = 0; i < m; i++) {
        int a, b;
        cin >> a >> b;
        G[a].push_back(b);
        G[b].push_back(a);
    }

    for (int i = 0; i < k; i++) {
        int u;
        cin >> u;
        res = 1e9, d = -1;
        if (G[u].empty()) {
            cout << 0 << "\n";
        } else {
            memset(dfsst, 0, sizeof(dfsst));
            Dijkstra(u);
            dfs(u);
            cout << res << "\n";
        }
    }

    return 0;
}
posted @ 2022-04-20 15:46  Xxaj5  阅读(18)  评论(0编辑  收藏  举报