noi.ac #241 distance

Saying that noi.ac in order to enhance the confidence of doing or konjac, behind this game a few questions to engage in a little water ah. .
While the first question the comparison drug. .

This T3. . . Water batch. . .

Pretreatment at each point directly to the root of the distance to other points not on line yet?

forget it. I'm done here. . .

Directly to the code. . .

#include <bits/stdc++.h>
#define ll long long
using namespace std;
const ll N = 10010;
ll head[N], Next[N<<1], ver[N<<1], edge[N], tot = 1;
ll Min(ll x, ll y) {
    return x < y ? x : y;
}
ll Max(ll x, ll y) {
    return x > y ? x : y;
}
template<class I>
inline void rd(I &x) {
    ll f = 1;
    char c = getchar();
    for(; c < '0' || c > '9'; c = getchar()) if(c == '-') f = -1;
    for(x = 0; c >= '0' && c <= '9'; x = (x << 3) + (x << 1) + (c & 15), c = getchar());
    x *= f;
}
ll dist[N][N];
void dfs(ll root, ll x, ll fa, ll dep) {
    dist[root][x] = dep;
    for (ll i = head[x]; i; i = Next[i]) {
        ll y = ver[i];
        if(y == fa) continue;
        dfs(root,y,x,dep + edge[i]);
    }
}
void add(ll x, ll y, ll z) {
    ver[++tot] = y;
    Next[tot] = head[x];
    head[x] = tot;
    edge[tot] = z;
}
ll n, q;
ll ans = 0;
int main() {
    rd(n), rd(q);
    for (ll i = 1; i < n; i++) {
        ll x, y, z;
        rd(x), rd(y), rd(z);
        add(x,y,z);
        add(y,x,z);
    }
    for (ll root = 1; root <= n; root++) {
        dfs(root, root, 0, 0);
    }
    while(q--) {
        ans = 0;
        ll x, y;
        rd(x), rd(y);
        for (ll i = 1; i <= n; i++)
            ans = Max(ans, Min(dist[x][i], dist[y][i]));
        printf("%lld\n",ans);
    }
    return 0;
}

Guess you like

Origin www.cnblogs.com/11haonb/p/11619797.html
241