1. 程式人生 > >bzoj3631 [JLOI2014]松鼠的新家

bzoj3631 [JLOI2014]松鼠的新家

void .so 。。 tag code ont n) span 之間

[JLOI2014]松鼠的新家

Time Limit: 10 Sec Memory Limit: 128 MB

Description

松鼠的新家是一棵樹,前幾天剛剛裝修了新家,新家有n個房間,並且有n-1根樹枝連接,每個房間都可以相互到達,且倆個房間之間的路線都是唯一的。天哪,他居然真的住在“樹”上。松鼠想邀請小熊維尼前來參觀,並且還指定一份參觀指南,他希望維尼能夠按照他的指南順序,先去a1,再去a2,……,最後到an,去參觀新家。
可是這樣會導致維尼重復走很多房間,懶惰的維尼不聽地推辭。可是松鼠告訴他,每走到一個房間,他就可以從房間拿一塊糖果吃。維尼是個饞家夥,立馬就答應了。
現在松鼠希望知道為了保證維尼有糖果吃,他需要在每一個房間各放至少多少個糖果。因為松鼠參觀指南上的最後一個房間an是餐廳,餐廳裏他準備了豐盛的大餐,所以當維尼在參觀的最後到達餐廳時就不需要再拿糖果吃了。

Input

第一行一個整數n,表示房間個數
第二行n個整數,依次描述a1-an
接下來n-1行,每行兩個整數x,y,表示標號x和y的兩個房間之間有樹枝相連。

Output

一共n行,第i行輸出標號為i的房間至少需要放多少個糖果,才能讓維尼有糖果吃。

Sample Input

5
1 4 5 3 2
1 2
2 4
2 3
4 5

Sample Output

1
2
1
2
1

HINT

2<= n <=300000

拒絕數據結構。。。。。樹上差分。。。
ans是子樹的和。。。
每次操作(s,t)
lca--,lca的爸爸--;
s++,t++;


#include<bits/stdc++.h>
using namespace std; const int maxn = 3e5 + 5; struct lpl{ int top, deep, fa, size, son, tag; }node[maxn]; int n, root, ini[maxn], ans[maxn]; vector<int> point[maxn]; inline void putit() { int x, y; scanf("%d", &n); for(int i = 1; i <= n; ++i) scanf("%d"
, &ini[i]); for(int i = 1; i < n; ++i){ scanf("%d%d", &x, &y); point[x].push_back(y); point[y].push_back(x); } } void dfs_1(int t) { node[t].size = 1; int lin = 0; for(int i = point[t].size() - 1; i >= 0; --i){ if(point[t][i] == node[t].fa) continue; node[point[t][i]].fa = t; node[point[t][i]].deep = node[t].deep + 1; dfs_1(point[t][i]); node[t].size += node[point[t][i]].size; if(lin < node[point[t][i]].size){ lin = node[point[t][i]].size; node[t].son = point[t][i]; } } } inline int LCA(int a, int b) { while(node[a].top != node[b].top){ if(node[node[a].top].deep < node[node[b].top].deep) swap(a, b); a = node[a].top; a = node[a].fa; } return (node[a].deep < node[b].deep) ? a : b; } inline void dfs_2(int t) { if(node[t].top == 0) node[t].top = t; node[node[t].son].top = node[t].top; for(int i = point[t].size() - 1; i >= 0; --i){ if(point[t][i] != node[t].fa) dfs_2(point[t][i]); } } inline void workk() { root = 1; dfs_1(root); dfs_2(root); for(int i = 2; i <= n; ++i){ int lca = LCA(ini[i], ini[i - 1]); node[lca].tag--; node[node[lca].fa].tag--; node[ini[i]].tag++; node[ini[i - 1]].tag++; } } void dfs_3(int t) { ans[t] += node[t].tag; for(int i = point[t].size() - 1; i >= 0; --i){ if(point[t][i] == node[t].fa) continue; dfs_3(point[t][i]); ans[t] += ans[point[t][i]]; } } inline void print() { dfs_3(root); for(int i = 2; i <= n; ++i) ans[ini[i]]--; for(int i = 1; i <= n; ++i) printf("%d\n", ans[i]); } int main() { putit(); workk(); print(); return 0; }

bzoj3631 [JLOI2014]松鼠的新家