1. 程式人生 > >Make It Equal(codeforces 1065c 貪心)

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)/~