CodeForces231C -- To Add or Not to Add

先贴上题目链接:http://codeforces.com/problemset/problem/231/C

直接说一下思路吧,二分搜索处理最大次数,因为要使a[i]为出现次数最多的那一个, 即搜索次数要小于k次,此外这题还需要一步的优化,即事先存一下a[1]~a[m]的和,在判定a[i]是否满足题意时,我们采取(m-1)*a[i] < a[i-1] - a[i-m] + k的操作,即满足那一堆数可以通过+k来变成出现次数最多的那个数。

以下是官方题解:

One of the main observations, needed to solve this problem, is that the second number in answer always coincides with someone aj. Let's see why it is true. Suppose, the second number of the answer is aj + d for someone j and aj + d ≠ ai for all i. This means, we increased some numbers, which is less than aj, so that they became equal to aj, and then all this numbers and some numbers, which is equal to aj, we increased to aj + d. But if we didn't increase all this numbers to aj + d and remain they equal to aj, we'd perform less operations and the answer would be better.

Due to this fact we can solve problem in a such manner. Sort array in non-decreasing order. Iterate over ai and calculate, what is the maximal number of ai we can obtain. For maximizing first number of answer, we must increase some lesser numbers to ai and perform not greater than k operations. It is obvious that firstly we should increase such aj that aiaj is minimal. So, if we can solve problem in O(n2), we would iterate j from i to 0 and increase aj to ai, while we could. But the solution must be faster, and we will use binary search. We will brute the number of numbers, which we must do equal to ai. Suppose we fix cnt this value. Now we have to check if we can do cntnumbers equal to ai by not greater than k operations. For doing this, let’s calculate . If this value not greater than k, we can do it. For calculating sum quickly, we can save prefix sums and than si - cnt + 1, i = sisicnt. Finally we solved this problem in O(n·logn).

AC代码:

#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
 
typedef long long LL;
const int INF = 0x3f3f3f3f;
const int N = 100010;
LL a[N], sum[N];
 
int main() {
   int n; LL k;
   while (~scanf("%d %I64d", &n, &k)) {
       for (int i = 1; i <= n; i++) scanf("%I64d", &a[i]);
       sort(a + 1, a + 1+n);
       int r = INF, l = 0;
       sum[1] = a[1];
       for (int i = 2; i <= n; i++) sum[i] = a[i] + sum[i-1];
       LL ans;
       while (r - l > 1) {
           int m = (r+l) / 2;
           if (m > n) { r = m; continue; }
           int flag = 0;
            for (int i = m; i <= n; i++) {
                if ((m-1)*a[i] - sum[i-1] +sum[i-m] <= k){
                    flag = 1; ans = a[i];
                    break;
                }
           }
           flag ? l = m : r = m;
       }
       printf("%d %I64d\n", l, ans);
    }
   return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值