题目链接;
HDU 2586 How far away?
题意:
和POJ 1986 Distance Queries一样的,包括数据范围。
分析:
这里建单向边就能过了。。。
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <math.h>
using namespace std;
typedef long long ll;
const int MAX_N = 40010;int T, n, m, total;
int head[MAX_N], id[MAX_N], in[MAX_N], dis[MAX_N];
int vis[MAX_N * 2], depth[MAX_N * 2], dp[MAX_N * 2][20];struct Edge {int v, w, next;
} edge[MAX_N * 2];void AddEdge (int u, int v, int w)
{edge[total].v = v, edge[total].w = w;edge[total].next = head[u];head[u] = total++;
}void dfs(int u, int p, int d, int& k)
{vis[k] = u, id[u] = k;depth[k++] = d;for (int i = head[u]; i != -1; i = edge[i].next) {int v = edge[i].v, w = edge[i].w;if (v == p) continue;dis[v] = dis[u] + w;dfs(v, u, d + 1, k);vis[k] = u;depth[k++] = d;}
}void RMQ(int root)
{int k = 0;dfs(root, -1, 0, k);int mm = k;int e = (int)log2(mm + 1.0);for (int i = 0; i < mm; ++i) { dp[i][0] = i; }for (int j = 1; j <= e; ++j) {for (int i = 0; i + (1 << j) - 1 < mm; ++i) {int nxt = i + (1 << (j - 1));if (depth[dp[i][j - 1]] < depth[dp[nxt][j - 1]]) {dp[i][j] = dp[i][j - 1];} else {dp[i][j] = dp[nxt][j - 1];}}}
}int LCA(int u, int v)
{int left = min(id[u], id[v]), right = max(id[u], id[v]);int e = (int)log2(right - left + 1.0);int pos, nxt = right - (1 << e) + 1;if (depth[dp[left][e]] < depth[dp[nxt][e]]) {pos = dp[left][e];} else {pos = dp[nxt][e];}return dis[u] + dis[v] - 2 * dis[vis[pos]];
}void init()
{total = 0;memset(in, 0, sizeof(in));memset(head, -1, sizeof(head));memset(dis, 0, sizeof(dis));
}int main()
{scanf("%d", &T);while (T--) {init();scanf("%d%d", &n, &m);for (int i = 1; i < n; ++i) {int u, v, w;scanf("%d%d%d", &u, &v, &w);AddEdge(u, v, w);in[v]++;}int root;for (int i = 1; i <= n; ++i) {if (in[i] == 0) {root = i;break;}}RMQ(root);while (m--) {int u, v;scanf("%d%d", &u, &v);printf("%d\n", LCA(u, v));}}return 0;
}