Make It Equal(codeforces 1065c 贪心)

There is a toy building consisting of n
n towers. Each tower consists of several cubes standing on each other. The i-th tower consists of hi 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≥n).。。。。。(题干不在这里罗列了,很麻烦)。
在这里插入图片描述
可算是把这个题做出来了,一到贪心题目。到底就是思路不行啊。感觉这里面有一些动态规划的意味。这里的前缀和数组是整个代码的核心。前缀和数组c[i]代表着高度为i的层数上面有多少层。举个例子吧:1 2 4 6 8,这是高度。。
1 2 3 4 5 6 7 8
4 3 3 2 2 1 1 0这就是前缀和数组的各个值。8上面没有了,就是0。能达到第七层,第六层的 只有一个,以此类推。长见识了。
代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;

const int maxx=2e5+10;
int a[maxx];
int b[maxx];
int c[maxx];
int n,k;

int main()
{
	while(cin>>n>>k)
	{
		memset(b,0,sizeof(b));
		for(int i=0;i<n;i++)
		{
			cin>>a[i];
			b[a[i]-1]++;//这里要记住减一
		}
		sort(a,a+n);
		if(a[0]==a[n-1])//如果一直都一样,就不用动了。
		{
			cout<<0<<endl;
			continue;
		}
		c[a[n-1]]=0;
		for(int i=a[n-1]-1;i>=a[0];i--)
		{
			c[i]=c[i+1]+b[i];//在第i层之上有多少个。
		}
		int ans=1;
		int temp=0;
		for(int i=a[n-1]-1;i>=a[0];i--)
		{
			if(temp+c[i]<=k)
			{
				temp+=c[i];
			}
			else//当大于k的时候,就ans++,更新temp
			{
				temp=c[i];
				ans++;
			}
		}
		cout<<ans<<endl;
	}
}

神奇的贪心。
努力加油a啊,(o)/~

猜你喜欢

转载自blog.csdn.net/starlet_kiss/article/details/83176986