標籤:
裸樹鏈剖分...
-------------------------------------------------------------------
#include<bits/stdc++.h> using namespace std; const int maxn = 300009; struct edge {int to;edge* next;} E[maxn << 1], *pit = E, *head[maxn]; inline void add(int u, int v) {pit->to = v;pit->next = head[u];head[u] = pit++;}#define addedge(u, v) add(u, v), add(v, u)#define M(l, r) (((l) + (r)) >> 1) int dep[maxn], size[maxn], son[maxn], fa[maxn], top[maxn], id[maxn], TOP, CK = 0; void dfs(int x) {son[x] = -(size[x] = 1);for(edge* e = head[x]; e; e = e->next) if(e->to != fa[x]) {dep[e->to] = dep[x] + 1;fa[e->to] = x;dfs(e->to);size[x] += size[e->to];if(!~son[x] || size[son[x]] < size[e->to]) son[x] = e->to;}} void DFS(int x) {top[x] = TOP;id[x] = ++CK;if(~son[x]) DFS(son[x]);for(edge* e = head[x]; e; e = e->next) if(e->to != son[x] && e->to != fa[x]) DFS(TOP = e->to);} void init() {dfs(dep[0] = 0);DFS(TOP = 0);} struct Node {Node *l, *r;int add;Node():add(0) {}} pool[maxn * 20], *pt = pool, *root; void build(Node* t, int l, int r) {if(r > l) {int m = M(l, r);build(t->l = pt++, l, m);build(t->r = pt++, m + 1, r);}} int L, R, N; void modify(Node* t, int l, int r) {if(L <= l && r <= R) t->add++;else {int m = M(l, r);if(L <= m) modify(t->l, l, m);if(m < R) modify(t->r, m + 1, r);}} int query(Node* t, int l, int r) {R += t->add;if(l == r) return R;int m = M(l, r);return L <= m ? query(t->l, l, m) : query(t->r, m + 1, r);} void change(int x, int y) {for(; top[x] != top[y]; x = fa[top[x]]) {if(dep[top[x]] < dep[top[y]]) swap(x, y);L = id[top[x]]; R = id[x];modify(root, 1, N);}if(dep[x] < dep[y]) swap(x, y);L = id[y]; R = id[x];modify(root, 1, N);} int path[maxn]; int main() {cin >> N;for(int i = 0; i < N; i++) scanf("%d", path + i), path[i]--;for(int i = 0; i < N - 1; i++) {int u, v; scanf("%d%d", &u, &v); --u; --v;addedge(u, v);}init();build(root = pt++, 1, N);for(int i = 1; i < N; i++) change(path[i - 1], path[i]);for(int i = 0; i < N; i++) {L = id[i]; R = 0;int t = query(root, 1, N);if(i != path[0]) t--;printf("%d\n", t);}return 0;}
-------------------------------------------------------------------
3631: [JLOI2014]松鼠的新家Time Limit: 10 Sec Memory Limit: 128 MB
Submit: 855 Solved: 412
[Submit][Status][Discuss]Description松鼠的新家是一棵樹,前幾天剛剛裝修了新家,新家有n個房間,並且有n-1根樹枝串連,每個房間都可以相互到達,且倆個房間之間的路線都是唯一的。天哪,他居然真的住在“樹”上。松鼠想邀請小熊維尼前來參觀,並且還指定一份參觀指南,他希望維尼能夠按照他的指南順序,先去a1,再去a2,……,最後到an,去參觀新家。可是這樣會導致維尼重複走很多房間,懶惰的維尼不聽地推辭。可是松鼠告訴他,每走到一個房間,他就可以從房間拿一塊糖果吃。維尼是個饞傢伙,立馬就答應了。現在松鼠希望知道為了保證維尼有糖果吃,他需要在每一個房間各放至少多少個糖果。因為松鼠參觀指南上的最後一個房間an是餐廳,餐廳裡他準備了豐盛的大餐,所以當維尼在參觀的最後到達餐廳時就不需要再拿糖果吃了。Input第一行一個整數n,表示房間個數第二行n個整數,依次描述a1-an接下來n-1行,每行兩個整數x,y,表示標號x和y的兩個房間之間有樹枝相連。Output一共n行,第i行輸出標號為i的房間至少需要放多少個糖果,才能讓維尼有糖果吃。Sample Input5
1 4 5 3 2
1 2
2 4
2 3
4 5
Sample Output1
2
1
2
1
HINT
2<= n <=300000
Source
BZOJ 3631: [JLOI2014]松鼠的新家( 樹鏈剖分 )