codevs1228 (dfs序+線段樹)
阿新 • • 發佈:2017-07-31
ret size str clas r+ cstring print sizeof scanf
- 總結:
第一次遇到dfs序的問題,對於一顆樹,記錄節點 i 開始搜索的序號 Left[i] 和結束搜索的序號 Righti[i],那麽序號在 Left[i] ~ Right[i] 之間的都是節點 i 子樹上的節點。
並且此序號與線段樹中 L~R 區間對應,在紙上模擬了幾遍確實如此,但暫時還未理解為何對應。
此題就是dfs序+線段樹的裸題
- 代碼:
#include<iostream>
#include<vector>
#include<cstring>
#include<cstdio>
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
using namespace std;
const int maxn = 1e5+5;
int dfs_order=0, Right[maxn], Left[maxn], vis[maxn];
int sumv[maxn<<2], lazy[maxn<<2];
vector<int> G[maxn];
void push_up(int l, int r, int rt)
{
sumv[rt]=sumv[rt<<1]+sumv[rt<<1|1];
}
void build(int l, int r, int rt)
{
if(l==r)
{
//cout<<l<<endl;
sumv[rt]=1;
return;
}
int m=(l+r)/2;
build(lson);
build(rson);
push_up(l, r, rt);
}
void update(int l, int r, int rt, int x, int v)
{
if(l==r)
{
sumv[rt]+=v;
return;
}
int m=(l+r)/2;
if(x<=m) update(lson, x, v);
if(m<x) update(rson, x, v);
push_up(l, r, rt);
}
int query(int l, int r, int rt, int ql, int qr)
{
if(ql<=l && r<=qr)
{
return sumv[rt];
}
int m=(l+r)/2, res;
if(qr<=m) res=query(lson, ql, qr);
else if(m<ql) res=query(rson, ql, qr);
else res=query(lson, ql, qr)+query(rson, ql, qr);
//cout<<"query "<<res<<endl;
return res;
}
void dfs(int x)
{
dfs_order++;
Left[x]=dfs_order;
//cout<<x<<" "<<Left[x]<<endl;
for(int i=0; i<G[x].size(); ++i)
{
if(!vis[G[x][i]]) {vis[G[x][i]]=1;dfs(G[x][i]);}
}
Right[x]=dfs_order;
}
int main()
{
int n, m;
scanf("%d", &n);
build(1, n, 1);
for(int i=1; i<n; ++i)
{
int u, v;
scanf("%d%d", &u, &v);
G[u].push_back(v);
G[v].push_back(u);
}
vis[1]=1;
dfs(1);
memset(vis, 0, sizeof vis);
scanf("%d", &m);
for(int i=1; i<=m; ++i)
{
char op;
int t;
cin>>op>>t;
if(op==‘Q‘)
{
//cout<<Left[t]<<" "<<Right[t]<<endl;
printf("%d\n", query(1, n, 1, Left[t], Right[t]));
}
else
{
if(!vis[t])
update(1, n, 1, Left[t], -1);
else
update(1, n, 1, Left[t], 1);
vis[t]=!vis[t];
}
}
return 0;
}
codevs1228 (dfs序+線段樹)