松鼠的新家是一棵树,前几天刚刚装修了新家,新家有n个房间,并且有n-1根树枝连接,每个房间都可以相互到达,且俩个房间之间的路线都是唯一的。天哪,他居然真的住在”树“上。
松鼠想邀请小熊维尼前来参观,并且还指定一份参观指南,他希望维尼能够按照他的指南顺序,先去a1,再去a2,......,最后到an,去参观新家。可是这样会导致维尼重复走很多房间,懒惰的维尼不停地推辞。可是松鼠告诉他,每走到一个房间,他就可以从房间拿一块糖果吃。
维尼是个馋家伙,立马就答应了。现在松鼠希望知道为了保证维尼有糖果吃,他需要在每一个房间各放至少多少个糖果。
因为松鼠参观指南上的最后一个房间an是餐厅,餐厅里他准备了丰盛的大餐,所以当维尼在参观的最后到达餐厅时就不需要再拿糖果吃了。
第一行一个整数n,表示房间个数第二行n个整数,依次描述a1-an
接下来n-1行,每行两个整数x,y,表示标号x和y的两个房间之间有树枝相连。
一共n行,第i行输出标号为i的房间至少需要放多少个糖果,才能让维尼有糖果吃。
2<= n <=300000
样例一输入:
5
1 4 5 3 2
1 2
2 4
2 3
4 5
样例一输出:
1
2
1
2
1
很明显的树上差分裸题,求出 $ A_{i} $ 和 $ A_{i+1} $ 的 $ lca $ 后点差分去做
就是需要注意 $ A_{i} \left( i \neq 1 \right) $ 会重复计算一次
所以输出答案时减掉
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <queue>
#include <list>
#include <map>
#define ll long long
#define ull unsigned long long
using namespace std;
const int mx_n = 300010;
int n;
int a[mx_n-1];
int w[mx_n];
int ans[mx_n];
int fa[mx_n][20],dep[mx_n];
int h[mx_n],to[mx_n<<1],nx[mx_n<<1],cnt;
inline void add(int f,int t) {
nx[++cnt] = h[f]; h[f] = cnt; to[cnt] = t;
nx[++cnt] = h[t]; h[t] = cnt; to[cnt] = f;
}
void dfs(int x) {
for(int i = h[x]; i; i = nx[i])
if(to[i] != fa[x][0]) {
fa[to[i]][0] = x;
dep[to[i]] = dep[x] + 1;
dfs(to[i]);
}
}
int LCA(int x,int y) {
if(dep[x] < dep[y]) swap(x,y);
for(int i = 19; i >= 0; i--)
if(dep[fa[x][i]] >= dep[y])
x = fa[x][i];
if(x == y) return x;
for(int i = 19; i >= 0; i--)
if(fa[x][i] != fa[y][i]) {
x = fa[x][i];
y = fa[y][i];
}
return fa[x][0];
}
int deal(int x) {
int now = w[x];
for(int i = h[x]; i; i = nx[i])
if(to[i] != fa[x][0]) {
now += deal(to[i]);
}
ans[x] = now;
return now;
}
int main() {
// freopen("testdata.in","r",stdin);
// freopen("1.out","w",stdout);
int c,b;
scanf("%d",&n);
for(int i = 1; i <= n; i++) {
scanf("%d",&a[i]);
}
for(int i = 1; i < n; i++) {
scanf("%d%d",&c,&b);
add(c,b);
}
add(0,1);
dfs(0);
for(int i = 1; i <= 19; i++)
for(int j = 1; j <= n; j++)
fa[j][i] = fa[fa[j][i-1]][i-1];
for(int i = 1; i < n; i++) {
int x = a[i], y = a[i+1];
int lca = LCA(x,y);
w[lca]--;
// cout << lca << '+' << endl;
w[x]++;
w[y]++;
w[fa[lca][0]]--;
}
deal(0);
for(int i = 1; i <= n; i++) {
printf("%d\n",i == a[1] ? ans[i] : ans[i]-1);
}
}
原文:https://www.cnblogs.com/ullio/p/9866256.html