DFS遍历树,把时间轴投到线段树上,单点查询~
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<string>
using namespace std;
const int maxn=1e6+14;
struct edge {
int to;
int next;
}Edge[maxn];
int head[maxn];
int tot;
int cnt;
int st[maxn];
int ed[maxn];
void init () {
cnt=0;
tot=0;
memset(head,-1,sizeof(head));
}
void addedge (int u,int v) {
Edge[tot].to=v;
Edge[tot].next=head[u];
head[u]=tot++;
}
void dfs (int u) {
++cnt;
st[u]=cnt;
for (int i=head[u];i!=-1;i=Edge[i].next)
dfs (Edge[i].to);
ed[u]=cnt;
}
struct node {
int l;
int r;
int val;
int lazy;
}segTree[maxn*4];
void update_same (int r,int v) {
if (r) {
segTree[r].val=v;
segTree[r].lazy=1;
}
}
void push_down (int r) {
if (segTree[r].lazy) {
update_same(r<<1,segTree[r].val);
update_same(r<<1|1,segTree[r].val);
segTree[r].lazy=0;
}
}
void build (int i,int l,int r) {
segTree[i].l=l;
segTree[i].r=r;
segTree[i].val=-1;
segTree[i].lazy=0;
if (l==r) return;
int mid=(l+r)>>1;
build(i<<1,l,mid);
build(i<<1|1,mid+1,r);
}
void update(int i,int l,int r,int v) {
if (segTree[i].l==l&&segTree[i].r==r) {
update_same(i,v);
return;
}
push_down(i);
int mid=(segTree[i].l+segTree[i].r)>>1;
if (r<=mid) update(i<<1,l,r,v);
else if (l>mid) update(i<<1|1,l,r,v);
else {
update(i<<1,l,mid,v);
update(i<<1|1,mid+1,r,v);
}
}
int query (int i,int u) {
if (segTree[i].l==u&&segTree[i].r==u) return segTree[i].val;
push_down(i);
int mid=(segTree[i].l+segTree[i].r)>>1;
if (u<=mid) return query(i<<1,u);
else return query(i<<1|1,u);
}
bool used[maxn];
int main () {
int n,m,t;
scanf ("%d",&t);
for (int i=1;i<=t;i++) {
printf ("Case #%d:\n",i);
int u,v;
memset(used,false,sizeof(used));
init ();
scanf ("%d",&n);
for (int j=1;j<n;j++) {
scanf ("%d %d",&u,&v);
used[u]=true;
addedge(v,u);
}
for (int j=1;j<=n;j++) {
if (!used[j]) {
dfs(j);
break;
}
}
build (1,1,cnt);
string s;
scanf ("%d",&m);
while (m--) {
cin>>s;
if (s=="C") {
scanf ("%d",&u);
printf ("%d\n",query(1,st[u]));
}
else {
scanf ("%d %d",&u,&v);
update(1,st[u],ed[u],v);
}
}
}
return 0;
}
来源:https://www.cnblogs.com/zhanglichen/p/12309451.html