比赛 |
CSP2022提高组 |
评测结果 |
WWWWWAAWWWWAAWWWWWWWWWWWW |
题目名称 |
数据传输 |
最终得分 |
16 |
用户昵称 |
zxhhh |
运行时间 |
4.394 s |
代码语言 |
C++ |
内存使用 |
0.00 MiB |
提交时间 |
2022-10-30 08:53:46 |
显示代码纯文本
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
typedef long long LL;
int n, q, k;
int hd[N], ver[N * 2], nxt[N * 2], idx, f[N][20], d[N];
LL fl[N][20], v[N];
inline void add (int x, int y) {
ver[++idx] = y;
nxt[idx] = hd[x];
hd[x] = idx;
}
void bfs () {
queue <int> q;
q.push(1); d[1] = 1;
while (q.size()) {
int t = q.front(); q.pop();
for (int i = hd[t]; i ;i = nxt[i]) {
int y = ver[i];
if (d[y]) continue;
d[y] = d[t] + 1; f[y][0] = t; fl[y][0] = v[y];
for (int j = 1;j <= log2(n);j++) {
f[y][j] = f[f[y][j - 1]][j - 1];
fl[y][j] = fl[y][j - 1] + fl[f[y][j - 1]][j - 1];
}
q.push(y);
}
}
}
int lca (int x, int y) {
if (d[x] < d[y]) swap(x, y);
for (int i = log2(n);i >= 0;i--) {
if (d[f[x][i]] >= d[y]) x = f[x][i];
}
if (x == y) return x;
for (int i = log2(n);i >= 0;i--) {
if (f[x][i] != f[y][i]) x = f[x][i], y = f[y][i];
}
return f[x][0];
}
LL l (int x, int ca) {
LL ltt = 0;
for (int i = log2(n);i >= 0;i--) {
if (d[f[x][i]] >= d[ca]) ltt += fl[x][i], x = f[x][i];
}
return ltt;
}
int main () {
freopen("csp2022_transmit.in", "r", stdin);
freopen("csp2022_transmit.out", "w", stdout);
scanf("%d%d%d", &n, &q, &k);
for (int i = 1;i <= n;i++) scanf("%lld", &v[i]);
for (int i = 1;i < n;i++) {
int a, b;
scanf("%d%d", &a, &b);
add(a, b); add(b, a);
}
bfs();
while (q--) {
int s, t;
scanf("%d%d", &s, &t);
int LCA = lca(s, t);
printf("%lld\n", l(s, LCA) + l(t, LCA) + v[LCA]);
}
return 0;
}