1081D - Maximum Distance - CodeForces Solution


dsu graphs shortest paths sortings *1800

Please click on ads to support us..

C++ Code:

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

#define all(x) begin(x), end(x)
#define rep(i, a, b) for(int i = a; i < b; i ++) 
typedef vector<int> vi;
typedef pair<int, int> pii;
#define fir first
#define sec second
#define pb push_back

struct E {
    int w, u, v;
};

vi fa;
int find(int p) {
    if(fa[p] == p) return p;
    return fa[p] = find(fa[p]);
}

vi dep, sz;

void dfs(int p, int q, vector<bool>& v, vector<vector<pii>>& g) {
    if(q != -1) dep[p] = dep[q] + 1;
    sz[p] = 0;
    if(v[p]) sz[p] = 1;
    for(auto [nxt, w] : g[p]) {
        if(nxt == q) continue ;
        dfs(nxt, p, v, g);
        sz[p] += sz[nxt];
    }
}

int main() {
    int n, m, k; cin >> n >> m >> k;
    vector<bool> v(n, 0);
    rep(i, 0, k) {
        int ai; cin >> ai; --ai;
        v[ai] = 1;
    }
    vector<vector<pii>> e(n), g(n);
    fa = vi(n, 0);
    iota(all(fa), 0);
    vector<E> es, e2;
    rep(i, 0, m) {
        int u, v, w; cin >> u >> v >> w; --u, --v;
        e[u].pb({v, w}), e[v].pb({u, w});
        es.pb({w, u, v});
    }
    sort(all(es), [&](E x, E y) {return x.w < y.w;});
    for(auto [w, u, v] : es) {
        int gu = find(u), gv = find(v);
        if(gu == gv) continue ; 
        fa[gu] = gv; 
        g[u].pb({v, w});
        g[v].pb({u, w});
        e2.pb({w, u, v});
    }
    reverse(all(e2)); 

    dep = sz = vi(n, 0);
    dfs(0, -1, v, g);
    int ans = 0;
    for(auto [w, u, v] : e2) {
        int x = u; if(dep[v] > dep[x]) x = v;
        if(sz[x] == 0 || sz[x] == k) continue ;
        else {ans = w; break ;}
    }
    rep(i, 0, k) cout << ans << " ";
    cout << endl;
}


Comments

Submit
0 Comments
More Questions

454A - Little Pony and Crystal Mine
2A - Winner
1622B - Berland Music
1139B - Chocolates
1371A - Magical Sticks
1253A - Single Push
706B - Interesting drink
1265A - Beautiful String
214A - System of Equations
287A - IQ Test
1108A - Two distinct points
1064A - Make a triangle
1245C - Constanze's Machine
1005A - Tanya and Stairways
1663F - In Every Generation
1108B - Divisors of Two Integers
1175A - From Hero to Zero
1141A - Game 23
1401B - Ternary Sequence
598A - Tricky Sum
519A - A and B and Chess
725B - Food on the Plane
154B - Colliders
127B - Canvas Frames
107B - Basketball Team
245A - System Administrator
698A - Vacations
1216B - Shooting
368B - Sereja and Suffixes
1665C - Tree Infection