第一题
思路:图的dfn算法
public class 第一题11 {
public static int cnt = 0;
public static int minFuel(int[] a, int[] b, int n) {
ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
for (int i = 0;i <= n;i++){
graph.add(new ArrayList<>());
}
for (int i = 0;i < a.length;i++){
graph.get(a[i]).add(b[i]);
graph.get(b[i]).add(a[i]);
}
int[] dfn = new int[n + 1];
int[] size = new int[n + 1];
int[] cost = new int[n + 1];
cnt = 0;
dfs(graph,0,dfn,size,cost);
return cost[0];
}
private static void dfs(ArrayList<ArrayList<Integer>> graph, int cur, int[] dfn, int[] size, int[] cost) {
dfn[cur] = ++cnt;
size[cur] = 1;
for (int next : graph.get(cur)){
if (dfn[next] == 0){
dfs(graph,next,dfn,size,cost);
size[cur] += size[next];
cost[cur] += cost[next];
cost[cur] += (size[next] + 4) / 5;
}
}
}
public static void main(String[] args) {
int[] a1 = { 0, 1, 1 };
int[] b1 = { 1, 2, 3 };
int n1 = 3;
System.out.println(minFuel(a1, b1, n1));
int[] a2 = { 1, 1, 1, 9, 9, 9, 9, 7, 8 };
int[] b2 = { 2, 0, 3, 1, 6, 5, 4, 0, 0 };
int n2 = 9;
System.out.println(minFuel(a2, b2, n2));
}
}
第二题
思路:找到最小值的位置,然后生成被最小值包围的新数组,再按分发糖果的解题思路计算,最后结果要减1
public class 第二题11 {
public static void main(String[] args) {
int[] ratings = {3,2,3,4,5,6};
int res = minCandy(ratings);
System.out.println(res);
}
public static int minCandy(int[] ratings){
int n = ratings.length;
int[] arr = new int[n + 1];
int index = 1;
while (index < n - 1){
if (ratings[index - 1] >= ratings[index] && ratings[index] <= ratings[index + 1]){
break;
}
index++;
}
if (index == n - 1){
index = ratings[index] > ratings[0] ? 0 : index;
}
System.arraycopy(ratings,index,arr,0,n - index);
System.arraycopy(ratings,0,arr,n - index,index);
arr[n] = ratings[index];
int[] left = new int[n + 1];
int[] right = new int[n + 1];
Arrays.fill(left,1);
Arrays.fill(right,1);
for (int i = 1;i <= n;i++){
if (arr[i] > arr[i - 1]){
left[i] += left[i - 1];
}
}
for (int i = n - 1;i >= 0;i--){
if (arr[i] > arr[i + 1]){
right[i] += right[i + 1];
}
}
int ans = 0;
for (int i = 0;i <= n;i++){
ans += Math.max(left[i],right[i]);
}
return ans - 1;
}
}