1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
| import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); PrintWriter pw=new PrintWriter(System.out); int t=sc.nextInt(); LCA lca=new LCA(); while(sc.hasNext()){ int n=sc.nextInt(); int[]deg=new int[n+1]; lca.init(); for(int i=0;i<n-1;i++){ int x=sc.nextInt(); int y=sc.nextInt(); deg[y]++; lca.adj[x].add(new Edge(x,y,1)); } int s=0; for(int i=1;i<=n;i++){ if(deg[i]==0)s=i; } lca.dfs(s, 0); lca.st(); int u=sc.nextInt(); int v=sc.nextInt(); pw.println(lca.lca(u, v)); pw.flush(); } } } class Edge{ int u; int v; int w; Edge(int u,int v,int w){ this.u=u; this.v=v; this.w=w; } } class LCA{ int maxn=10010; int maxm=20; ArrayList<Edge>[]adj; int tot; boolean[]vis; int[]pow; int[]first; int[]R; int[]ver; int[]dir; int[][]dp; LCA(){ adj=new ArrayList[2*maxn]; for(int i=0;i<maxn;i++)adj[i]=new ArrayList<Edge>(); tot=0; vis=new boolean[maxn]; dir=new int[maxn]; dp=new int[2*maxn][maxm]; ver=new int[2*maxn]; first=new int[maxn]; pow=new int[maxm]; R=new int[2*maxn]; pow[0]=1; for(int i=1;i<maxm;i++){ pow[i]=pow[i-1]*2; } } void init(){ for(int i=0;i<maxn;i++)adj[i].clear(); tot=0; Arrays.fill(vis, false); Arrays.fill(dir, 0); Arrays.fill(ver, 0); Arrays.fill(first, 0); Arrays.fill(R, 0); for(int i=0;i<2*maxn;i++) for(int j=0;j<maxm;j++)dp[i][j]=0; } void dfs(int u ,int dep){ vis[u] = true; ver[++tot] = u; first[u] = tot; R[tot] = dep; for(int k=0;k<adj[u].size();k++){ Edge child=adj[u].get(k); if(!vis[child.v] ){ int v = child.v , w = child.w; dir[v] = dir[u] + w; dfs(v,dep+1); ver[++tot] = u; R[tot] = dep; } } } void st(){ int len=tot; int K = (int)(Math.log((double)(len)) / Math.log(2.0)); for(int i=1;i<=len;i++)dp[i][0]=i; for(int j=1;j<=K;j++){ for(int i=1;i+pow[j]-1<=len;i++){ int a=dp[i][j-1]; int b=dp[i+pow[j-1]][j-1]; if(R[a]<R[b])dp[i][j]=a; else dp[i][j]=b; } } } int lca(int u ,int v) { int x = first[u] , y = first[v]; if(x > y) { int t=x; x=y; y=t; } int res = RMQ(x,y); return ver[res]; } int RMQ(int x ,int y) { int K = (int)(Math.log((double)(y-x+1)) / Math.log(2.0)); int a = dp[x][K] , b = dp[y-pow[K]+1][K]; if(R[a] < R[b]) return a; else return b; } void add_diredge(int u, int v, int c){ adj[u].add(new Edge(u,v,c)); } }
|