# dfs序题目练习

http://blog.csdn.net/qq_24489717/article/details/50569644

dfs序比较重要的性质：一棵子树的所有节点在dfs序里是连续一段，主要就是利用这个性质来解题.

Poj 3321:

#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string.h>
using namespace std;
typedef long long LL;
const int N = 500005;
struct Edge{
int v,next;
}edge[N];
int in[N],out[N];
bool have[N];
int cnt;
void init(){
tot = 0;
cnt = 0;
memset(c,0,sizeof(c));
}
}
void dfs(int u){
in[u] = ++cnt;
dfs(edge[k].v);
}
out[u] = cnt;
}
int lowbit(int x){
return x&(-x);
}
int getsum(int id){
int sum = 0;
for(int i=id;i>=1;i-=lowbit(i)){
sum+=c[i];
}
return sum;
}
void update(int id,int x){
for(int i=id;i<=cnt;i+=lowbit(i)){
c[i]+=x;
}
}
int main()
{
int n,m;
while(scanf("%d",&n)!=EOF){
init();
for(int i=0;i<n-1;i++){
int u,v;
scanf("%d%d",&u,&v);
}
dfs(1);
/*for(int i=1;i<=n;i++){
printf("%d %d\n",in[i],out[i]);
}*/
for(int i=1;i<=n;i++){
have[i] = 1;
update(in[i],1);
}
int q;
scanf("%d",&q);
while(q--){
char s[5];
int x;
scanf("%s%d",s,&x);
if(s[0]=='Q'){
printf("%d\n",getsum(out[x])-getsum(in[x]-1));
}else{
if(have[x]) update(in[x],-1);
else update(in[x],1);
have[x] = !have[x];
}
}
}
return 0;
}

hdu 3886 :

#pragma comment(linker,"/STACK:1024000000,1024000000")
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string.h>
using namespace std;
typedef long long LL;
const int N = 500005;
struct Edge{
int v,next;
}edge[N];
int in[N],out[N];
bool have[N];
int cnt;
void init(){
tot = 0;
cnt = 0;
memset(c,0,sizeof(c));
}
}
void dfs(int u,int fa){
in[u] = ++cnt;
if(edge[k].v == fa) continue;
dfs(edge[k].v,u);
}
out[u] = cnt;
}
int lowbit(int x){
return x&(-x);
}
int getsum(int id){
int sum = 0;
for(int i=id;i>=1;i-=lowbit(i)){
sum+=c[i];
}
return sum;
}
void update(int id,int x){
for(int i=id;i<=cnt;i+=lowbit(i)){
c[i]+=x;
}
}
int main()
{
int n,q;
while(scanf("%d%d",&n,&q)!=EOF,n+q){
init();
for(int i=1;i<n;i++){
int u,v;
scanf("%d%d",&u,&v);
}
dfs(q,-1);
bool flag = true;
for(int i=1;i<=n;i++){
if(!flag) printf(" ");
printf("%d",getsum(out[i])-getsum(in[i]-1));
flag = false;
update(in[i],1);
}
printf("\n");
}
return 0;
}

hdu 5692:利用DFS序将树形结构转换成为线段树.便于维护和查找.

http://www.cnblogs.com/liyinggang/p/5925196.html

hdu 5468:DFS序+容斥原理 ,求解每个结点下面与其互质的结点的个数。

http://www.cnblogs.com/liyinggang/p/5926105.html

bzoj 2819:DFS序+博弈+树状数组+lca,维护树上的一条路上的异或值.

http://www.cnblogs.com/liyinggang/p/5927232.html

update中...

posted @ 2016-09-29 21:46  樱花庄的龙之介大人  阅读(...)  评论(...编辑  收藏