跳到正文

题解

题解 - CF812C Sagheer and Nubian Market

tacocat约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年3月31日
收录
2025年12月12日
更新
2026年11月13日
篇幅
约 3 分钟
获赞
2
题目
CF812C

版本

  1. v1当前

思路

二分答案板子题,但是注意需要开 long long。

可以直接二分能买到的纪念品数量,那么我们就需要一个辅助函数来计算总花费(参数中的 kk 为要买的纪念品数量):

C++
LL calc(int k) {
    for (int i = 1; i <= n; i ++ )
        b[i] = (LL)a[i] + (LL)i * k;
    
    LL res = 0;
    std::sort(b + 1, b + n + 1);
    
    for (int i = 1; i <= k; i ++ )
        res += b[i];
    
    return res;
}

那么 check 函数就可以直接判断是否小于等于 SS(代码中的 mm 就是题目中的 SS,kk 和 calc 中的 kk 表达的是同一个意思):

C++
bool check(int k) {
    return calc(k) <= m;
}

当然,最后要判断是否有可行解,即 check(r),如果有可行解,直接输出 r calc(r) 即可,否则输出 0 0。

代码

最终把上述代码汇总,可得:

C++
#include <cstdio>
#include <algorithm>

typedef long long LL;
const int N = 1e5 + 5;

int n, m;
int a[N];
LL b[N];

LL calc(int k) {
    for (int i = 1; i <= n; i ++ )
        b[i] = (LL)a[i] + (LL)i * k;
    
    LL res = 0;
    std::sort(b + 1, b + n + 1);
    
    for (int i = 1; i <= k; i ++ )
        res += b[i];
    
    return res;
}

bool check(int k) {
    return calc(k) <= m;
}

void inp() {
    scanf("%d%d", &n, &m);

    for (int i = 1; i <= n; i ++ )
        scanf("%d", &a[i]);
}

void work() {
    int l = 1, r = n;

    while (l < r) {
        int mid = l + r + 1 >> 1;
        
        if (check(mid))
            l = mid;
        else
            r = mid - 1;
    }

    if (check(r))
        printf("%d %lld\n", r, calc(r));
    else
        puts("0 0");
}

int main() {
    inp();
    work();

    return 0;
}

完结撒花!

原文
存档评论1 条抓取于