首页 技术 正文
技术 2022年11月18日
0 收藏 571 点赞 2,730 浏览 1357 个字

经典LCA操作。。

贴AC代码

import java.lang.reflect.Array;
import java.util.*;
public class POJ1330 {
// 并查集部分
static int[] p;
static int find(int u){
if(p[u]!=u){
p[u] = find(p[u]);
}
return p[u];
}
static class Edge{
int to;
int next;
}
// 链式前向星
static int[] head;
static Edge[] edges; static boolean[] vist;
// 所求LCA的两点
static int qfrom;
static int qto;
// 找根
static boolean[] isroot; static boolean LCA(int u){
// 在以自己为根的子树中计算LCA
// 如果没找到就回溯到父节点,再向下去兄弟子树计算
// 先建立以自己为代表的并查集
p[u]=u;
vist[u]=true; for(int k=head[u];k>=0;k=edges[k].next){
int to = edges[k].to;
if(!vist[to]) {
// 计算子树
// 如果在某棵子树计算过程中算出结果,就返回true
if(LCA(to))
return true;
// 子树计算完,把子树的并查集代表节点设为当前节点
p[to] = u;
}
}
// 所有子树计算完毕,还没发现结果
// 试试用当前节点计算结果
if(u == qfrom){
if(vist[qto]){
System.out.println(find(qto));
return true;
}
}else if(u==qto){
if(vist[qfrom]){
System.out.println(find(qfrom));
return true;
}
} // 还是没算出结果,向上回溯,准备去兄弟子树计算
return false;
} public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
while (n-- > 0){
int m = sc.nextInt();
p = new int[m+1];
head = new int[m+1];
Arrays.fill(head,-1);
edges = new Edge[m];
vist = new boolean[m+1];
isroot = new boolean[m+1];
Arrays.fill(isroot,true);
// 链式前向星构有向图
for(int i=0;i<m-1;i++){
int from = sc.nextInt();
int to = sc.nextInt();
Edge edge = new Edge();
edge.to=to;
edge.next=head[from];
edges[i]=edge;
head[from]=i;
// 有父节点的不是根
isroot[to]=false;
}
qfrom = sc.nextInt();
qto = sc.nextInt();
// 找根
int root=0;
for(int i=1;i<isroot.length;i++){
if(isroot[i]) {
root = i;
break;
}
}
// 计算LCA
LCA(root);
}
}
}

  

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,962
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,486
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,331
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,114
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,747
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,781