题解 - CF812C Sagheer and Nubian Market
思路
二分答案板子题,但是注意需要开 long long。
可以直接二分能买到的纪念品数量,那么我们就需要一个辅助函数来计算总花费(参数中的
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 函数就可以直接判断是否小于等于
bool check(int k) {
return calc(k) <= m;
}
当然,最后要判断是否有可行解,即 check(r),如果有可行解,直接输出 r calc(r) 即可,否则输出 0 0。
代码
最终把上述代码汇总,可得:
#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;
}