codeforces Educational Codeforces Round 52 div2C - Make It Equal

版权声明:若转载请附上原博客链接,谢谢! https://blog.csdn.net/Link_Ray/article/details/83211990

题意

n n 座塔,每座塔都有一个高度 h h ,我们需要经过若干次操作使得这些塔的高度相同,操作定义为: 每次可以定义一个水平线 h 0 h_0 ,使得 i = 1 n m a x ( 0 , h i h 0 ) < = k \sum_{i=1}^{n}max(0,h_i-h_0) <= k 。问最少需要多少次操作使得所有塔的高度相同。
1 n 2 × 1 0 5 , 1 k 1 0 9 , 1 h i 2 × 1 0 5 1\leq n \leq 2\times10^5,1\leq k \leq 10^9,1 \leq h_i \leq 2\times10^5
在这里插入图片描述

题解

将所有的塔安装高度从小到大排序放入数组 H H ,记录下最小的高度 m i n _ h min\_h ,最大的高度 m a x _ h max\_h ,然后从大到小逐一枚举高度 h h ,因为每次高度减一,说明每次都是一层一层的削塔,所以可以很容易得出每次耗费的 c o s t = n p o s ( h ) + 1 cost = n-pos(h)+1

p o s ( h ) pos(h) 代表 i n t ( u p p e r _ b o u n d ( H + 1 H + 1 + n h ) H ) int(upper\_bound(H+1,H+1+n,h)-H) 。找出比 h h 高的塔中下标最小的那个塔的位置。 比如1,2,2,4, h = 2 h = 2 p o s ( h ) = 4 pos(h)=4

s u m k sumk 定义为当前总花费,当 s u m k + c o s t > k sumk+cost > k 时我们就需要增加一次操作。然后令 s u m k = c o s t sumk = 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;
}

猜你喜欢

转载自blog.csdn.net/Link_Ray/article/details/83211990