Java代码得分是100,但是有四组数据RE,不知道哪里有问题
查看原帖
Java代码得分是100,但是有四组数据RE,不知道哪里有问题
276210
我爱发育楼主2023/5/27 16:30

Java代码得分是100,但是有四组数据RE,不知道哪里有问题

import java.util.*;
import java.io.*;

public class Main {
		static int INF = 1000000007;
		static int N = 501000 , M = 2*N;
		static int[] depth = new int[N];
		static int[][] fa = new int[N][20];//最大2^19次方
		static int n,m,start;
		static int[] h = new int[N],e = new int[M],ne = new int[M];
		static int idx;
		static void add(int a,int b) {
			e[idx] = b;
			ne[idx] = h[a];
			h[a] = idx++;
		}
		//st表预处理(计算倍增数组)
		static void dfs(int u,int father) {
			
			for(int k=1;k<=19;k++) {
				fa[u][k] = fa[fa[u][k-1]][k-1];
			}

			for(int i=h[u];i!=-1;i=ne[i]) {
				int j = e[i];
				if(j==father) continue;
				depth[j] = depth[u] + 1;
			    fa[j][0] = u;
				dfs(j,u);
			}
			
		}
		
		//lca求公共祖先
		static int lca(int a,int b) {
			if(depth[a]<depth[b]) {
				int t = a;
				a = b;
				b = t;
			}
			//1.把a和b移到同一层
			for(int i=19;i>=0;i--) {
				if(depth[fa[a][i]]>=depth[b])
					a = fa[a][i];
			}
			if(a==b) return b;
			//2.a和b同时向上找到最近公共祖先的下一个
			for(int i=19;i>=0;i--) {
				if(fa[a][i] != fa[b][i]) {
					a = fa[a][i];
					b = fa[b][i];
				}	
			}
			return fa[a][0];
		}
		
		public static void main(String[] sss) throws IOException{
			Read sc = new Read();
			PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
			Arrays.fill(h,-1);
			n = sc.nextInt();
			m = sc.nextInt();
			start = sc.nextInt();
			for(int i=1;i<=n-1;i++) {
				int a = sc.nextInt();
				int b = sc.nextInt();
				add(a,b);
				add(b,a);
			}
			depth[start] = 1;
			fa[start][0] = 0;
			dfs(start,-1);
			
			while(m-->0) {
				int x = sc.nextInt();
				int y = sc.nextInt();
				int ans = lca(x,y);
				out.println(ans);
			}
			out.flush();
		}
		
}
class Read{
    StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));

    int nextInt() throws IOException {
        st.nextToken();
        return (int)st.nval;
    }
}

2023/5/27 16:30
加载中...