dfs序 線段樹 樹狀陣列 蘋果樹

2021-09-14 03:59:05 字數 1013 閱讀 3922

給出乙個蘋果樹,每個節點一開始都有蘋果

c x,如果x點有蘋果,則拿掉,如果沒有,則新長出乙個

q x,查詢x點與它的所有後代分支一共有幾個蘋果

第一行是節點總數n (n ≤ 100,000) ,

接下來n-1行表示n-1條邊 根節點為1

for every inquiry, output the correspond answer per line

31 2

1 33

q 1c 2

q 13

2解:列出dfs序,由dfs序性質(一棵子樹所有節點在dfs序裡是連續的一段)可將原題轉化為:

在dfs序中單點修改,區間求和,樹狀陣列/線段樹即可。

這裡樓主使用的是更快更簡潔的樹狀陣列

#includeusing namespace std;

#define lowbit(x) x&(-x)

inline int read()

while(ch>='0'&&ch<='9')

return x*f;

}const int n=1e5+10;

int t[n],n,m,first[n],cnt,st[n],ed[n],dfn[n],tot,q[n];

struct nodee[n*2];

inline int add(int u,int v)

inline void update(int x,int v)

}inline int query(int x)

return sum;

}inline void dfs(int x)

ed[x]=tot;

}int main()

dfs(1);

m=read();

for(int i=1;i<=n;++i) update(st[i],1),q[i]=1;

while(m--)

if(op=='q')

} return 0;

}

POj 3321 樹狀陣列蘋果樹

output for every inquiry,output the correspond answer per line.sample input 3 1 2 1 3 3 q 1 c 2 q 1 sample output 3 2 樹狀陣列的中級應用,求一段子樹,都覺得和樹狀陣列沾不上邊,但是嘛...

hdu3887dfs序 樹狀陣列 線段樹

題目 大意 求在當前點的所有後代中,後代點的序號大小 當前點的序號大小,並統計他們的個數,這就是f i 思路 dfs序 樹狀陣列 線段樹 dfs序 dfs序 dfs是深度優先的,所以對於乙個點,它會先遍歷完它的所有子節點,再去遍歷他的兄弟節點以及其他所以對於一棵樹的dfs序來說,這個點和他所有的子節...

dfs序 樹狀陣列

the first line contains an integer n n 100,000 which is the number of the forks in the tree.output for every inquiry,output the correspond answer per ...