1 条题解

  • 1
    @ 2025-3-2 16:31:59
    #include <cstdio>
    #include <iostream>
    #include <cstring>
    #include <algorithm>
    using namespace std;
    
    const int N = 500010;
    long long int a[N], s[N]; // a[i]表示第i个蛋糕的大小,s[i]表示前i个蛋糕的大小之和
    int n, t;
    long long int ans1, ans2; // ans1表示贝茜拿走的蛋糕大小之和,ans2表示埃尔茜拿走的蛋糕大小之和
    
    int main()
    {
        scanf("%d", &t);
        while (t--)
        {
            ans1 = 0, ans2 = 0; // 初始化ans1和ans2
            scanf("%d", &n);
            for (int i = 1; i <= n; i++)
            {
                scanf("%Ld", &a[i]);
                s[i] = s[i - 1] + a[i]; // 预处理前缀和
            }
            int cnt = (n - 2) / 2; // 计算埃尔茜需要拿走的蛋糕数量
            int i = 1, j = n; // 记录贝茜拿走的蛋糕范围
            for (int k = 0; k <= cnt; k++) // 枚举埃尔茜拿走的蛋糕的所有可能情况
            {
                // 从左边开始拿k个蛋糕,总和为s[k]
                // 从右边开始拿cnt-k个蛋糕,总和为s[n] - s[n - cnt + k]
                long long int sum = s[k] + s[n] - s[n - cnt + k]; // 计算埃尔茜拿走的总蛋糕大小
                if (sum > ans2) // 如果当前情况比之前的情况更优
                {
                    ans2 = sum; // 更新答案
                    i = k + 1, j = n - cnt + k; // 计算更新贝茜拿走的蛋糕范围(如果利用ans2求ans1就不用存范围了)
                }
            }
            ans1 = s[j] - s[i - 1]; // 计算贝茜拿走的蛋糕大小之和(也可写为ans1 = s[n] - ans2;)
            printf("%Ld %Ld\n", ans1, ans2);
        }
        return 0;
    }
    

    信息

    ID
    5553
    时间
    1000ms
    内存
    256MiB
    难度
    10
    标签
    递交数
    4
    已通过
    4
    上传者