C. Make It Equal
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
There is a toy building consisting of n towers. Each tower consists of several cubes standing on each other. The i-th tower consists of hihi cubes, so it has height hi.
Let’s define operation slice on some height H as following: for each tower i, if its height is greater than H, then remove some top cubes to make tower’s height equal to H. Cost of one “slice” equals to the total number of removed cubes from all towers.
Let’s name slice as good one if its cost is lower or equal to k (k≥n).
Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so.
Input
The first line contains two integers nn and kk (1≤n≤2⋅10^ 5, n≤k≤10^ 9) — the number of towers and the restriction on slices, respectively.
The second line contains nn space separated integers h1,h2,…,hn (1≤hi≤2⋅10^5) — the initial heights of towers.
Output
Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth.
Examples
inputCopy
5 5
3 1 2 2 4
outputCopy
2
inputCopy
4 5
2 3 4 5
outputCopy
2
Note
In the first example it’s optimal to make 2slices. The first slice is on height 2(its cost is 3), and the second one is on height 1 (its cost is 4).
中文大意:给你一排参差不齐的塔,让你水平方向依次切掉上面的,且每一次切的总数不能超过k,问你最少切多少刀使得全部塔一样高。
这是一道很好的题,定义是贪心,本来也是这么想的,sort复杂度O(nlog(n))
但是,后来我发现,这道题根本不需要sort ,直接O(n)线性就行了
题解:我们只需把它横过来,那不就是1维了吗》?(感觉真的还是简单的啊) 差分稍微一下
那么看看代码就能理解~~
#include<algorithm>
#include<bitset>
#include<cctype>
#include<cerrno>
#include<cfloat>
#include<ciso646>
#include<climits>
#include<clocale>
#include<cmath>
#include<complex>
#include<csignal>
#include<csetjmp>
#include<cstdarg>
#include<cstddef>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<ctime>
#include<cwchar>
#include<cwctype>
#include<deque>
#include<exception>
#include<fstream>
#include<functional>
#include<limits>
#include<list>
#include<locale>
#include<map>
#include<memory>
#include<new>
#include<numeric>
#include<iomanip>
#include<ios>
#include<iosfwd>
#include<iostream>
#include<istream>
#include<iterator>
#include<ostream>
#include<queue>
#include<set>
#include<sstream>
#include<stack>
#include<stdexcept>
#include<streambuf>
#include<string>
#include<typeinfo>
#include<utility>
#include<valarray>
#include<vector>
using namespace std;
long long h[200005];
int main()
{
int n, k;
cin >> n >> k;
int m = 0;
int Min = 2e9;
for (int i = 1 ; i <= n ; ++ i)
{
int x;
cin >> x;
++ h[1];
-- h[x + 1];
m = max(m, x);
Min = min(Min, x);
}
for (int i = 2 ; i <= m ; ++ i)
h[i] += h[i - 1];
int S = 0;
int Ans = 0;
for (int i = m ; i > Min ; )
{
while ( (S += h[i]) <= k && i > Min)
-- i;
S = 0;
++ Ans;
}
cout << Ans << endl;
return 0;
}