记录编号 269404 评测结果 AAAAAAAAAA
题目名称 [HZOI 2015]简单的最近公共祖先 最终得分 100
用户昵称 GravatarSky_miner 是否通过 通过
代码语言 C++ 运行时间 4.585 s
提交时间 2016-06-13 16:28:06 内存使用 114.73 MiB
显示代码纯文本
  1. #include<cstdio>
  2. #include<cstring>
  3. #include<cstdlib>
  4. using namespace std;
  5. inline void read(int &x){
  6. x=0;char ch;
  7. while(ch=getchar(),ch<'!');
  8. while(x=10*x+ch-'0',ch=getchar(),ch>'!');
  9. }
  10. inline int cat_max(const int &a,const int &b){return a>b ? a:b;}
  11. inline int cat_min(const int &a,const int &b){return a<b ? a:b;}
  12. const int maxn = 2000010;
  13. struct Edge{
  14. int to,next;
  15. Edge(){to=next=0;}
  16. }G[maxn<<1];
  17. int head[maxn],cnt;
  18. void add(int u,int v){
  19. G[++cnt].to=v;
  20. G[cnt].next=head[u];
  21. head[u]=cnt;
  22. }
  23. struct line{
  24. int flag,u,top;
  25. bool is_up;
  26. line(){
  27. is_up = false;
  28. }
  29. }lne[maxn];
  30. int deep[maxn],siz[maxn],fa[maxn],map[maxn],son[maxn],top[maxn];
  31. void dfs(int u){
  32. siz[u] = 1;
  33. for(int i=head[u];i;i=G[i].next){
  34. if( G[i].to == fa[u] ) continue;
  35. int v = G[i].to;
  36. fa[v] = u;
  37. deep[v] = deep[u] + 1;
  38. dfs(v);
  39. siz[u] += siz[v];
  40. if( siz[son[u]] < siz[v] )
  41. son[u] = v;
  42. }
  43. }
  44. int tim;
  45. void dfs(int u,int tp){
  46. if(u==tp){
  47. lne[++tim].top=u;
  48. map[u]=tim;
  49. }else map[u] = map[tp];
  50. top[u]=tp;
  51. if(son[u]) dfs(son[u],tp);
  52. for(int i=head[u];i;i=G[i].next){
  53. int v = G[i].to;
  54. if( son[u]==v || fa[u]==v )continue;
  55. dfs(v,v);
  56. }
  57. }
  58. int n,m,upsum=1;
  59. void update(int u){
  60. while(u){
  61. int tmp = map[u];
  62. if(lne[tmp].flag != upsum){
  63. lne[tmp].u = lne[tmp].top;
  64. lne[tmp].flag = upsum;
  65. lne[tmp].is_up = false;
  66. }
  67. lne[tmp].is_up = true;
  68. if( deep[lne[tmp].u] < deep[u] ) lne[tmp].u=u;
  69. u = fa[ top[u] ];
  70. }
  71. }
  72. int Query(int u){
  73. while(u){
  74. int tmp = map[u];
  75. if(lne[tmp].flag == upsum){
  76. if( lne[tmp].is_up ){
  77. if(deep[lne[tmp].u] <= deep[u]) return lne[tmp].u;
  78. else return u;
  79. }
  80.  
  81. }
  82. u=fa[top[u]];
  83. }
  84. return -1;
  85. }
  86. int main(){
  87. int __size__=128<<20;
  88. char *__p__=(char*)malloc(__size__)+__size__;
  89. __asm__("movl %0, %%esp\n"::"r"(__p__));
  90. freopen("get_tree.in","r",stdin);
  91. freopen("get_tree.out","w",stdout);
  92. read(n),read(m);
  93. int u,v;
  94. for(int i=1;i<n;i++){
  95. read(u),read(v);
  96. add(u,v);add(v,u);
  97. }
  98. deep[1] = 1;
  99. dfs(1);
  100. dfs(1,1);
  101. int x;char ch;
  102. for(int i=1;i<=m;i++){
  103. while(ch=getchar(),ch<'!');
  104. if(ch=='C') ++upsum;
  105. else if(ch=='M') read(x),update(x);
  106. else if(ch=='Q') read(x),printf("%d\n",Query(x));
  107. }
  108. fclose(stdin);fclose(stdout);
  109. return 0;
  110. }