奇安信两道题代码
方法可能不太好,好歹用例都过了
import java.util.*;
public class Qianxin {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String ppidstr = sc.nextLine();
String pidstr = sc.nextLine();
int target = sc.nextInt();
String[] ppidarr = ppidstr.split(" ");
String[] pidarr = pidstr.split(" ");
int[] ppid = new int[ppidarr.length];
int[] pid = new int[ppid.length];
HashMap<Integer, List<Integer>> map = new HashMap<>();
for (int i = 0; i < pidarr.length; i++) {
ppid[i] = Integer.valueOf(ppidarr[i]);
pid[i] = Integer.valueOf(pidarr[i]);
if(!map.containsKey(pid[i])) {
List<Integer> list = new ArrayList<>();
list.add(ppid[i]);
map.put(pid[i], list);
}else{
List<Integer> list = map.get(pid[i]);
list.add(ppid[i]);
map.put(pid[i],list);
}
}
// System.out.println(map);
long count = 0;
Queue<Integer> q = new LinkedList<>();
for (int i = 0; i < ppid.length; i++) {
if(ppid[i] == target){
count++;
}
}
if(map.containsKey(target)){
q.offer(target);
}
// System.out.println(count);
while(!q.isEmpty()){
int size = q.size();
for (int i = 0; i < size; i++) {
int num = q.poll();
if(map.containsKey(num)){
List<Integer> list = map.get(num);
for (int j = 0; j < list.size(); j++) {
q.offer(list.get(j));
count++;
}
}
}
}
System.out.println(count);
}
/*
3 1 5 21 10
0 3 3 1 5
5
* */
public static void main2(String[] args) {
Scanner sc = new Scanner(System.in);
int ceng = sc.nextInt();
long size =(long) Math.pow(2, ceng) - 1;
int[] nums = new int[(int)size];
for (int i = 0; i < size; i++) {
nums[i] = sc.nextInt();
}
int son1 = sc.nextInt();
int son2 = sc.nextInt();
int i1 = -1, i2=-1;
int c1 = 0, c2 = 0;
ceng = 0;
for (int i = 0; i < size; i++) {
if(i >= Math.pow(2, ceng) - 1) ceng++;
if(son1 == nums[i]){ i1 = i; c1 = ceng;}
if(son2 == nums[i]) {i2 = i; c2 = ceng;}
}
if(i1==-1 || i2==-1){
System.out.println(-1);
return;
}
// System.out.println("i1:" + i1 + " c1:"+ c1);
// System.out.println(findParentIndex(i1));
// System.out.println("i2:" + i2 + " c2:"+ c2);
// System.out.println(findParentIndex(i2));
while(c1 > c2){
i1 = findParentIndex(i1);
c1--;
}
while(c1 < c2){
i2 = findParentIndex(i2);
c2--;
}
while(i1 != i2){
i1 = findParentIndex(i1);
i2 = findParentIndex(i2);
}
System.out.println(nums[i1]);
}
private static int findParentIndex(int i){
return (i - 1) / 2;
}
}
