fork(1) download
  1. #include<cstdio>
  2. #include<cstring>
  3. #include<iostream>
  4. using namespace std;
  5. #define MAX 1010
  6. #define MAXLVL 12
  7. #define rl(x) scanf("%d",&x)
  8. int parent[MAX+12],dp[MAXLVL+2][MAX],depth[MAXLVL+12];
  9. int LCA(int u, int v)
  10. {
  11. if(depth[u] < depth[v])
  12. swap(u,v);
  13. int diff = depth[u] - depth[v];
  14. for(int i=0; i<MAXLVL; i++)
  15. if( (diff>>i)&1 )
  16. {
  17. u = dp[i][u];
  18. }
  19. if(u == v)
  20. return u;
  21. for(int i=MAXLVL-1; i>=0; i--)
  22. if(dp[i][u] != dp[i][v])
  23. {
  24. u = dp[i][u];
  25. v = dp[i][v];
  26. }
  27. return dp[0][u];
  28. }
  29. int main()
  30. {
  31. int t,ca=1;
  32. rl(t);
  33. while(ca<=t)
  34. {
  35. int n,m;
  36. rl(n);
  37. memset(depth,0,sizeof depth);
  38. parent[0]=-1;
  39. for(int i=0;i<n;i++)
  40. {
  41. rl(m);
  42. while(m--)
  43. {
  44. int x,y;
  45. rl(y);
  46. y--;
  47. depth[y]=depth[i]+1;
  48. parent[y]=i;
  49. }
  50. }
  51. for(int i=0;i<MAXLVL;i++)
  52. for(int j=0; j<n; j++)
  53. dp[i][j]=-1;
  54. for(int i=0;i<n;i++)
  55. dp[0][i]=parent[i];
  56. for(int i=1; i<MAXLVL; i++)
  57. for(int j=0; j<n; j++)
  58. if(dp[i-1][j] != -1)
  59. dp[i][j] = dp[i-1][dp[i-1][j]];
  60. printf("Case %d:\n",ca);
  61. int q,x,y;
  62. rl(q);
  63. while(q--)
  64. {
  65. cin>>x>>y;
  66. x--,y--;
  67. cout<<LCA(x,y)+1<<endl;
  68. }
  69. ca++;
  70.  
  71. }
  72. }
Success #stdin #stdout 0s 2792KB
stdin
1
7
3 2 3 4
0
3 5 6 7
0
0
0
0
2
5 7
2 7
stdout
Case 1:
3
1