| 记录编号 |
397262 |
评测结果 |
AAAAA |
| 题目名称 |
2281.[HZOI 2015]白黑树 |
最终得分 |
100 |
| 用户昵称 |
AntiLeaf |
是否通过 |
通过 |
| 代码语言 |
C++ |
运行时间 |
0.323 s |
| 提交时间 |
2017-04-19 21:32:50 |
内存使用 |
21.10 MiB |
显示代码纯文本
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
const int maxn=200010;
void dfs(int);
void RMQ_init();
int LCA(int,int);
template<typename cmp>struct binary_heap{
priority_queue<int,vector<int>,cmp>q1,q2;
void push(int x){q1.push(x);}
void erase(int x){q2.push(x);}
int top(){
while(!q2.empty()&&q1.top()==q2.top()){
q1.pop();
q2.pop();
}
return q1.top();
}
bool empty(){
while(!q2.empty()&&q1.top()==q2.top()){
q1.pop();
q2.pop();
}
return q1.empty();
}
};
vector<int>G[maxn];
int f[maxn][20],log_tbl[maxn];
int p[maxn],d[maxn],dfn[maxn],tim=0;
struct cmp1{cmp1(){}bool operator()(int x,int y){return dfn[x]<dfn[y];}};
binary_heap<cmp1>heap1;
struct cmp2{cmp2(){}bool operator()(int x,int y){return dfn[x]>dfn[y];}};
binary_heap<cmp2>heap2;
bool col[maxn]={false};
char c;
int n,m,x,y,last;
int main(){
freopen("C_Tree.in","r",stdin);
freopen("C_Tree.out","w",stdout);
scanf("%d%d",&n,&m);
for(int i=1;i<n;i++){
scanf("%d%d",&x,&y);
G[x].push_back(y);
G[y].push_back(x);
}
dfs(1);
RMQ_init();
while(m--){
scanf(" %c%d",&c,&x);
if(c=='M'){
if(col[x]){
heap1.erase(x);
heap2.erase(x);
}
else{
heap1.push(x);
heap2.push(x);
}
col[x]^=true;
}
else{
if(heap1.empty())printf("-1\n");
else{
int u=LCA(x,heap1.top()),v=LCA(x,heap2.top());
printf("%d\n",d[u]<d[v]?u:v);
}
}
}
return 0;
}
void dfs(int x){
f[tim][0]=last;
last=x;
dfn[x]=++tim;
d[x]=d[p[x]]+1;
for(int i=0;i<(int)G[x].size();i++)if(G[x][i]!=p[x]){
p[G[x][i]]=x;
dfs(G[x][i]);
}
last=p[x];
}
void RMQ_init(){
log_tbl[0]=-1;
for(int i=1;i<n;i++)log_tbl[i]=log_tbl[i>>1]+1;
for(int j=1;(1<<j)<n;j++)for(int i=1;i+(1<<j)-1<n;i++)
f[i][j]=(d[f[i][j-1]]<d[f[i+(1<<(j-1))][j-1]]?f[i][j-1]:f[i+(1<<(j-1))][j-1]);
}
int LCA(int l,int r){
if(l==r)return l;
l=dfn[l];r=dfn[r];
if(l>r)swap(l,r);
r--;
int k=log_tbl[r-l+1];
return d[f[l][k]]<d[f[r-(1<<k)+1][k]]?f[l][k]:f[r-(1<<k)+1][k];
}