There is a toy building consisting of nn towers. Each tower consists of several cubes standing on each other. The ii-th tower consists of hihicubes, so it has height hihi.
Let's define operation slice on some height HH as following: for each tower ii, if its height is greater than HH, then remove some top cubes to make tower's height equal to HH. 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 kk (k≥nk≥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.
The first line contains two integers nn and kk (1≤n≤2⋅1051≤n≤2⋅105, n≤k≤109n≤k≤109) — the number of towers and the restriction on slices, respectively.
The second line contains nn space separated integers h1,h2,…,hnh1,h2,…,hn (1≤hi≤2⋅1051≤hi≤2⋅105) — the initial heights of towers.
Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth.
5 5
3 1 2 2 4
2
4 5
2 3 4 5
2
In the first example it's optimal to make 22 slices. The first slice is on height 22 (its cost is 33), and the second one is on height 11 (its cost is 44).
cf的一道特烦的题,超时到爆,然后发现可以用前缀和。
首先把所有塔的高度减去其中的最小值,问题就变成了将塔消完所需要的步数。(可以不减,那样最后就是>min而不是>0)
用前缀和做一个数组brr,即这么高的塔有几个;
然后从最大的判断相减就好了,(注意前一个高度等于原来的加后一个)(相加和都不超过给定的k)
#include<iostream> #include<algorithm> using namespace std; int brr[200001]={0}; int main() { int n,m; cin>>n>>m; int arr[200001]; int min=200001,max=0; for(int i=1;i<=n;i++) { cin>>arr[i]; if(arr[i]<min) min=arr[i]; if(arr[i]>max) max=arr[i]; } for(int i=1;i<=n;i++) { brr[arr[i]-min]++; } int k=0,sum=0; for(int i=max-min;i>0;i--) { k+=brr[i]; brr[i-1]+=brr[i]; if(k>m) { brr[i-1]-=brr[i]; i++; k=0; sum++; } } if(k>0) sum++; cout<<sum; }