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

[BZOJ3631][JLOI2014]松鼠的新家

能夠 style div int input pac 連接 bsp lca

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


非常裸的樹上差分。

註意最後把算了兩遍的減1


#include <iostream>
#include <cstdio>
#include <queue>
#include <cstdlib>
using namespace std;
#define reg register 
inline int read() {
    int res = 0;char ch=getchar();
    while(!isdigit(ch)) ch=getchar();
    while(isdigit(ch)) res=(res<<3)+(res<<1
)+(ch^48), ch=getchar(); return res; } #define N 300005 int n; struct edge { int nxt, to; }ed[N*2]; int head[N], cnt; inline void add(int x, int y) { ed[++cnt] = (edge){head[x], y}; head[x] = cnt; } int a[N]; bool vis[N]; int dep[N]; int f[N][20]; inline void bfs() { dep[0] = -1; dep[1] = 1; queue <int> q; q.push(1); while(!q.empty()) { int x = q.front();q.pop(); for (reg int i = head[x] ; i ; i = ed[i].nxt) { int to = ed[i].to; if (dep[to]) continue; dep[to] = dep[x] + 1; q.push(to); f[to][0] = x; for (reg int j = 1 ; j <= 19 ; j ++) f[to][j] = f[f[to][j-1]][j-1]; } } } inline int lca(int x, int y) { if (dep[x] < dep[y]) swap(x, y); for (reg int i = 19 ; i >= 0 ; i --) if (dep[f[x][i]] >= dep[y]) x = f[x][i]; if (x == y) return x; for (reg int i = 19 ; i >= 0 ; i --) if (f[x][i] != f[y][i]) x = f[x][i], y = f[y][i]; return f[x][0]; } int cf[N], ans[N]; void dfs(int x) { ans[x] = cf[x]; for (reg int i = head[x] ; i ; i = ed[i].nxt) { int to = ed[i].to; if (to == f[x][0]) continue; dfs(to); ans[x] += ans[to]; } } int main() { n = read(); for (reg int i = 1 ; i <= n ; i ++) a[i] = read(); for (reg int i = 1 ; i < n ; i ++) { int x = read(), y = read(); add(x, y), add(y, x); } bfs(); for (reg int i = 1 ; i <= n - 1 ; i ++) { int x = a[i], y = a[i+1]; int l = lca(x, y); cf[x]++, cf[y]++; cf[l]--, cf[f[l][0]]--; } dfs(1); for (reg int i = 2 ; i <= n ; i ++) ans[a[i]]--; for (reg int i = 1 ; i <= n ; i ++) printf("%d\n", ans[i]); return 0; }

[BZOJ3631][JLOI2014]松鼠的新家