HDU 2586 How far way?

Posted mrzdtz220

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU 2586 How far way?相关的知识,希望对你有一定的参考价值。

 

传送门

继续水板子题...

技术图片
#include <bits/stdc++.h>
using namespace std;

inline int read() {
    int x = 0, f = 1; char ch = getchar();
    while (ch < 0 || ch > 9) { if (ch == -) f = -1; ch = getchar(); }
    while (ch >= 0 && ch <= 9) { x = x * 10 + ch - 0; ch = getchar(); }
    return x * f;
}

const int maxn = 5e5 + 10;

struct Edge { int to, next, c; } edge[2 * maxn];
int cnt, head[maxn];
struct Qedge { int to, next; } qedge[2 * maxn];
int qcnt, qhead[maxn], n, m;
int lca[maxn], dep[maxn], par[maxn];
bool vis[maxn];
inline void addedge(int u, int v, int c) {
    edge[++cnt].to = v;
    edge[cnt].c = c;
    edge[cnt].next = head[u];
    head[u] = cnt; 
}
inline void addqedge(int u, int v) {
    qedge[++qcnt].to = v;
    qedge[qcnt].next = qhead[u];
    qhead[u] = qcnt;
}
int getfa(int x) { return x == par[x] ? x : par[x] = getfa(par[x]); }

void dfs(int u) {
    par[u] = u;
    vis[u] = 1; 
    for (int i = head[u]; i; i = edge[i].next) {
        int v = edge[i].to;
        if (!vis[v]) {
            dep[v] = dep[u] + edge[i].c;
            dfs(v);
            par[v] = u;
        } 
    }
    for (int i = qhead[u]; i; i = qedge[i].next) {
        int v = qedge[i].to;
        if (vis[v]) {
            lca[i] = getfa(v);
            if (i % 2) lca[i + 1] = lca[i];
            else lca[i-1] = lca[i];
        }
    }
}

int main() {
    int T = read();
    while (T--) {
        n = read();m = read();
        memset(head, 0, sizeof(head));
        memset(qhead, 0, sizeof(qhead));
        memset(vis, 0, sizeof(vis));
        memset(lca, 0, sizeof(lca));
        memset(dep, 0, sizeof(dep));
        cnt = qcnt = 0;
        for (int i = 0; i < n - 1; i++)
        {
            int u = read(), v = read(), c = read();
            addedge(u, v, c);
            addedge(v, u, c);
        }
        for (int i = 0; i < m; i++)
        {
            int u = read(), v = read();
            addqedge(u, v);
            addqedge(v, u);
        }
        dfs(1);
        for (int i = 1; i <= m; i++)
        {
            int ans = dep[qedge[2 * i].to] - 2 * dep[lca[2 * i]] + dep[qedge[2 * i - 1].to];
            printf("%d\n", ans);
        }
    }
    return 0;
}
View Code

 

以上是关于HDU 2586 How far way?的主要内容,如果未能解决你的问题,请参考以下文章

hdu 2586 How far away?(树链剖分+前缀和)

HDU - 2586 How far away ?

HDU2586How far away? LCA

hdu 2586 How far away ? 离线LCA

HDU - 2586 How far away ?(暴力 | LCA)

hdu 2586 How far away ?