題目來源:http://acm.hdu.edu.cn/showproblem.php?pid=3974
★開學之後又有好久沒寫博客了,快一個月了,寫了一下以前寫過的題目,居然忘記怎麼寫了。。。
不會寫的原因是MLE 沒有把head數組清0,調了一晚上,枯了
題意:
現在有一個公司,裏面有n個員工,員工之間有上級和下屬的關係。上級得到了任務 他會立刻和其所有下屬轉手幹這份工作(把之前的事拋在一邊)。然後給你兩個操作,①:給某個員工一個工作 ②:問某個員工在幹什麼工作
思路:
在dfs遍歷樹的過程中 記錄下每個父節點的起始時間和終止時間
(點左邊的數字是起始時間,右邊的數字是終止時間)
然後很容易發現,起始時間 和 終止時間 之間的點就是 父節點的子節點
所以我們更新的時候在這個區間更新就好了
單點查詢的時候,查詢 起始點 終止點 都行
剩下的就是基本的線段樹操作了~詳見代碼
代碼:
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
#include<map>
#include<stack>
#include<queue>
#include<set>
#include<vector>
#define ls k<<1,l,mid
#define rs k<<1|1,mid+1,r
using namespace std;
typedef long long LL;
const int maxn=5e4+5;
const int mod=1e9+7;
const int inf=0x7ffff;
const double pi=acos(-1);
const double eps=1e-8;
int n,m,cnt;
struct node
{
int to,nex;
}g[maxn];
int head[maxn],st[maxn],en[maxn];
int v[maxn<<2],lazy[maxn<<2];
bool vis[maxn];
template<class t>
inline void read(t &x)
{
char c;x=1;
while((c=getchar())<'0'||c>'9') if(c=='-') x=-1;
t res=c-'0';
while((c=getchar())>='0'&&c<='9') res=res*10+c-'0';
x*=res;
}
void addedge(int x,int y)
{
g[++cnt].to=y;
g[cnt].nex=head[x];
head[x]=cnt;
}
void dfs(int k)
{
// cout<<k<<'x'<<endl;
st[k]=++cnt;
for(int i=head[k];i;i=g[i].nex){
dfs(g[i].to);
}
en[k]=cnt;
}
void build(int k,int l,int r)
{
lazy[k]=0;
v[k]=-1;
if(l==r) return ;
int mid=l+r>>1;
build(ls); build(rs);
}
void push_down(int k,int l,int r,int mid)
{
if(lazy[k]){
lazy[k<<1]=lazy[k<<1|1]=lazy[k];
v[k<<1]=v[k<<1|1]=lazy[k];
lazy[k]=0;
}
}
void update(int k,int l,int r,int x,int y,int val)
{
if(x<=l&&r<=y){
v[k]=val;
lazy[k]=val;
return ;
}
int mid=l+r>>1;
push_down(k,l,r,mid);
if(mid>=x) update(ls,x,y,val);
if(mid<y) update(rs,x,y,val);
}
int query(int k,int l,int r,int pos)
{
if(l==r) return v[k];
int mid=l+r>>1;
push_down(k,l,r,mid);
if(mid>=pos) return query(ls,pos);
return query(rs,pos);
}
int main()
{
int t;
read(t);
int cas=0;
while(t--){
read(n);
printf("Case #%d:\n",++cas);
memset(vis,0,sizeof vis);
memset(head,0,sizeof head);
cnt=0;
for(int i=1;i<n;i++){
int a,b;
read(a); read(b);
addedge(b,a);
vis[a]=1;
}
cnt=0;
for(int i=1;i<=n;i++){
if(!vis[i]){
dfs(i);
break;
}
}
build(1,1,cnt);
char s[10];
int p,q;
read(m);
// for(int i=1;i<=n;i++){
// cout<<st[i]<<' '<<en[i]<<endl;
// }
while(m--){
scanf("%s %d",s,&p);
if(s[0]=='C'){
printf("%d\n",query(1,1,cnt,st[p]));
}
else{
read(q);
update(1,1,cnt,st[p],en[p],q);
}
}
}
return 0;
}