原题链接
题意:
给出点的个数n和操作数Q,给出n个点的权值,给出n-1条边的连接方式,要及时回答Q个询问,询问包括三个数字k,x,y,如果k=0,那么就将x点的权值改为y,如果k!=0,就求出x到y的最短路径上经过所有点(含本身)的第k大的权值。
思路:
利用在线LCA树上倍增算法,求x,y的LCA然后分别从x,y出发往上走记录到lca经过的所有点的权值,然后sort排序输出就行算法用时171ms
#include<stdio.h>
#include<iostream>
#include<math.h>
#include<algorithm>
#include<string.h>
#include<queue>
using namespace std;
const int maxn = 500000;
int tot;
int head[maxn], nxt[maxn *2], ver[maxn *2], wei[maxn *2];
int f[maxn][100];
int dep[maxn];
int ans[maxn];
void addedge(int u, int v)
{
nxt[++tot] = head[u], head[u] = tot, ver[tot] = v;
nxt[++tot] = head[v], head[v] = tot, ver[tot] = u;
}
int t;queue<int>q;
void bfs()
{
q.push(1); dep[1] = 1;
while (q.size())
{
int x = q.front(); q.pop();
for (int i = head[x]; i != -1; i = nxt[i])
{
int y = ver[i];
if (dep[y])continue;
dep[y] = dep[x] + 1;
f[y][0] = x;
for (int j = 1; j <= t; j++)
{
f[y][j] = f[f[y][j - 1]][j - 1];
}
q.push(y);
}
}
}
int lca(int x , int y)
{
if (dep[x] > dep[y])swap(x, y);
for (int i = t; i >= 0; i--)
{
if (dep[f[y][i]] >= dep[x])
y = f[y][i];
}
if (x == y)return x;
for (int i = t; i >= 0; i--)
{
if (f[x][i] != f[y][i])
{
x = f[x][i];
y = f[y][i];
}
}
return f[x][0];
}
int main()
{
int n, Q;
scanf("%d%d", &n, &Q);
memset(head, -1, sizeof(head));
memset(dep, 0, sizeof(dep));
for (int i = 1; i <= n; i++)
{
scanf("%d", &wei[i]);
}
for (int i = 1; i < n; i++)
{
int x, y;
scanf("%d%d", &x,&y);
addedge(x, y);
}
t = (int)(log(n) / log(2)) + 1;
bfs();
for (int j = 1; j <= Q; j++)
{
int k, x, y;
scanf("%d%d%d", &k, &x, &y);
if (k == 0)wei[x] = y;
else
{
int LCA = lca(x, y);
int cnt = 0;
ans[cnt++] = wei[x];
ans[cnt++] = wei[y];
if(LCA!=x&&LCA!=y)ans[cnt++] = wei[LCA];
for (;f[x][0]!=LCA&&x!=LCA;)
{
ans[cnt++] = wei[f[x][0]];
x = f[x][0];
}
for (; f[y][0] != LCA&&y!=LCA;)
{
ans[cnt++] = wei[f[y][0]];
y = f[y][0];
}
sort(ans, ans + cnt);
/*for (int i = 0; i < cnt; i++)
{
cout << ans[i] << ' ';
}*/
//cout << endl;
if (cnt - k < 0)printf("invalid request!\n");
else printf("%d\n", ans[cnt - k]);
}
}
}