题意

nn座塔,每座塔都有一个高度hh,我们需要经过若干次操作使得这些塔的高度相同,操作定义为: 每次可以定义一个水平线h0h_0,使得i=1nmax(0,hih0)<=k\sum_{i=1}^{n}max(0,h_i-h_0) <= k。问最少需要多少次操作使得所有塔的高度相同。
1n2×105,1k109,1hi2×1051\leq n \leq 2\times10^5,1\leq k \leq 10^9,1 \leq h_i \leq 2\times10^5
codeforces Educational Codeforces Round 52 div2C - Make It Equal

题解

将所有的塔安装高度从小到大排序放入数组HH,记录下最小的高度min_hmin\_h,最大的高度max_hmax\_h,然后从大到小逐一枚举高度hh,因为每次高度减一,说明每次都是一层一层的削塔,所以可以很容易得出每次耗费的cost=npos(h)+1cost = n-pos(h)+1

pos(h)pos(h)代表int(upper_bound(H+1H+1+nh)H)int(upper\_bound(H+1,H+1+n,h)-H)。找出比hh高的塔中下标最小的那个塔的位置。 比如1,2,2,4,h=2h = 2pos(h)=4pos(h)=4

sumksumk定义为当前总花费,当sumk+cost>ksumk+cost > k时我们就需要增加一次操作。然后令sumk=costsumk = cost

代码

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 2e5+5;
ll h[maxn], n, k;
ll ok(ll x) {
	int pos = int(upper_bound(h+1,h+1+n,x)-h);
	return (n-pos+1);
}
int main() {
	scanf("%lld%lld", &n,&k);
	for(int i = 1; i <= n; ++i)
		scanf("%lld", &h[i]);
	sort(h+1,h+1+n);
	int _min = h[1];
	int cnt = 0;
	ll sumk = 0;
	for(ll i = h[n]; i >= _min; --i) {
		int t = ok(i);
		if(sumk + t > k) 
			cnt++, sumk = t;
		else 
			sumk += t;
	}
	if(sumk > 0)
		cnt++;
	cout << cnt << endl;
	return 0;
}

相关文章: