Featured image of post AcWing 5995.挖矿

AcWing 5995.挖矿

AcWing 5995.挖矿

题目

image-20250410192846955

image-20250410192856254

答案:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        // 读取输入
        int n = sc.nextInt(); // 矿洞数
        int m = sc.nextInt(); // 最大步数
        int[] L = new int[2000005]; // 记录左侧矿洞
        int[] R = new int[2000005]; // 记录右侧矿洞
        int[] Ls = new int[2000005]; // 左侧前缀和
        int[] Rs = new int[2000005]; // 右侧前缀和
        int zero = 0; // 记录起点 0 处的矿洞数量
        
        // 读取矿洞信息
        for (int i = 0; i < n; i++) {
            int t = sc.nextInt();
            if (t < 0) {
                L[-t]++; // 左侧
            } else if (t > 0) {
                R[t]++; // 右侧
            } else {
                zero++; // 记录起点0
            }
        }

        // 计算前缀和
        for (int i = 1; i <= 2000000; i++) {
            Ls[i] = L[i] + Ls[i - 1];
            Rs[i] = R[i] + Rs[i - 1];
        }

        int ans = 0; // 记录最大可收集矿石数
        
        // 枚举向左走的步数
        for (int i = 0; i <= m; i++) {
            int j = (m - i) / 2; // 剩余步数一半用于回头
            if (i < j) j = m - 2 * i;

            // 计算当前走法的矿石数
            int sums = Rs[i] + Ls[Math.max(0, j)];
            ans = Math.max(ans, sums);
        }

        ans += zero; // 加上起点0的矿石数量

        // 输出答案
        System.out.println(ans);
    }
}
NovaBryan的博客
使用 Hugo 构建
主题 StackJimmy 设计