C. Make It Equal

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_38081836/article/details/83027895

题意:给出n个高度,问最少通过多少次代价最多为k的消减能够使得所有的高度相同。(代价:消减的总高度)


题解:可以考虑从他的最高高度开始一阶一阶的减,一直减到最小的那个高度,通过记录每次减一的代价与k进行比较即可得出结果。


a c c o d e : ac code:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define met(a, b) memset(a, b, sizeof(a))
#define rep(i, a, b) for(int i = a; i <= b; i++)
#define per(i, a, b) for(int i = a; i >= b; i--)
#define pb push_back
const int maxn = 1e6 + 10;
const int inf = 0x3f3f3f3f;

ll n, k, h[maxn], cnt[maxn];

int main() {
    while(~scanf("%lld%lld", &n, &k)) {
        met(cnt, 0);
        ll MIN = inf, MAX = 0;
        rep(i, 1, n) scanf("%lld", &h[i]), MIN = min(h[i], MIN), cnt[h[i]]++, MAX = max(MAX, h[i]);
        ll ans = 0, sum = 0;
        per(i, MAX, MIN + 1) {
            cnt[i] += cnt[i + 1];
            if(sum + cnt[i] > k) {
                ans++;
                sum = cnt[i];
            } else {
                sum += cnt[i];
            }
        }
        printf("%lld\n", ans + (sum > 0));
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/m0_38081836/article/details/83027895