题目描述
示例:
输入:
6 2 4 6
5 3 4 6 4 9
1 2
1 2 3
1 3 4
2 3 5
4 5 6
输出:
16
样例说明
第 1 天至第 5 天,将编号 1 与编号 2 的作物杂交,得到编号 3 的作物种子。
第 6 天至第 10 天,将编号 1 与编号 3 的作物杂交,得到编号 4 的作物种子。
第 6 天至第 9 天,将编号 2 与编号 3 的作物杂交,得到编号 5 的作物种子。
第 11 天至第 16 天,将编号 4 与编号 5 的作物杂交,得到编号 6 的作物种子。
总共花费 16 天。
参考代码
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
static int n,m,k,t;
static int[] time;
static boolean[] Had;
static Map<Integer, int[]> programme= new HashMap<>();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
k = sc.nextInt();
t = sc.nextInt();
time = new int[n+1];
Had = new boolean[n+1];
for (int i = 1; i <= n; i++) {
time[i] = sc.nextInt();
}
for (int i = 0; i < m; i++) {
int temp = sc.nextInt();
Had[temp]=true;
}
for (int i = 0; i < k; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
programme.put(c, new int[]{a, b});
}
sc.close();
System.out.println(find(t));
}
public static int find(int index) {
if (Had[index]) {
return 0;
}else {
Had[index]=true;
int xTime = find(programme.get(index)[0]);
int yTime = find(programme.get(index)[1]);
int x=time[programme.get(index)[0]];
int y=time[programme.get(index)[1]];
return Math.max(x, y)+Math.max(xTime,yTime);//杂交时间+双亲杂交时间长的一个
}
}
}