[树状数组优化DP]bzoj3594 - cool's Blog

[树状数组优化DP]bzoj3594

cool posted @ 2016年4月10日 16:04 in DP , 369 阅读

3594: [Scoi2014]方伯伯的玉米田

Time Limit: 60 Sec  Memory Limit: 128 MB
Submit: 955  Solved: 405
[Submit][Status][Discuss]

Description

方伯伯在自己的农田边散步,他突然发现田里的一排玉米非常的不美。
这排玉米一共有N株,它们的高度参差不齐。
方伯伯认为单调不下降序列很美,所以他决定先把一些玉米拔高,再把破坏美感的玉米拔除掉,使得剩下的玉米的高度构成一个单调不下降序列。
方伯伯可以选择一个区间,把这个区间的玉米全部拔高1单位高度,他可以进行最多K次这样的操作。拔玉米则可以随意选择一个集合的玉米拔掉。
问能最多剩多少株玉米,来构成一排美丽的玉米。

Input


第1行包含2个整数n,K,分别表示这排玉米的数目以及最多可进行多少次操作。
第2行包含n个整数,第i个数表示这排玉米,从左到右第i株玉米的高度ai。

Output


输出1个整数,最多剩下的玉米数。

Sample Input

3 1
2 1 3

Sample Output

3

HINT

 

1 < N < 10000,1 < K ≤ 500,1 ≤ ai ≤5000

 

 

这题的dp状态很容易想到dp[i][j]表示前i棵玉米用了j次加+1最多留下几棵

不过转移还是挺难想的

dp[i][j]=max(dp[k][x])+1(k<i x<=j a[k]+l<=a[i]+j)

为什么是a[k]+l<=a[i]+j?

可以这么想,对于每次加其实都可以加到尾,这种加法是不会劣于只加中间一段的

 

因为要求不降,所以如果你只加中间一段,会导致后面一段的数和前面的数的差变大,从而可能导致使用更多的加操作。

推出式子以后,我们发现这是n*n*k*k的显然炸了。

不过他要求max,显然就想到了用数据结构维护,那当然使用最短的树状数组了。

因为有三个限制(k<i x<=j a[k]+l<=a[i]+j),难道要用三维树状数组?log^3!magic!

显然因为当算到i的时候,只有1-(i-1)会对答案产生影响,所以我们就可以像类似完全背包一样去掉一维,然后将j倒着扫一遍。这样就变成了二维树状数组了。

如果还是正着扫 那dp[i][j]有可能就从dp[i][j-1]转移 显然是不对的啦。

附上代码:

#include <cstdio>
#include <algorithm>
using namespace std; 
int a[10010],g[510][6000],n,K,ans;
int query(int x,int y)
{
	int t = 0;
	for (;x;x -= x&-x)
		for (int j = y;j;j -= j&-j)
			if (g[x][j]>t) t = g[x][j];
	return t;
}
void update(int x,int y,int d)
{
	for (;x<=K+1;x+=x&-x)
		for (int j = y;j<=5600;j+=j&-j)
			if (d>g[x][j]) g[x][j] = d;
}
 
int main()
{
	scanf("%d%d",&n,&K);
	for (int i = 1;i <= n;i++)
		scanf("%d",&a[i]);
	for (int i = 1;i <= n;i++)
		for (int j = K;j >= 0;j--)
		{
			int tmp = query(j+1,a[i]+j);
			if (ans < tmp+1) ans = tmp+1;
			update(j+1,a[i]+j,tmp+1);
		}
	printf("%d",ans);
	return 0;
}

dp的水平还是不够,zjoiday1T3根本没想到是dp,唉还是太年轻

AP SSC History Quest 说:
2022年9月15日 23:26

History can guide learners to see trends and processes from a broader, holistic perspective and to understand them. Through History, they come into contact with other cultures and societies and in this way they gain a more holistic understanding of the contemporary world and their place in this broader context. Telugu Medium, AP SSC History Question Paper English Medium & Urdu Medium Students of the State Board can download the AP 10th History Model Paper 2023 Pdf with Answers designed based on the revised syllabus and curriculum of the course. Class teachers and leading institutional experts are designed and suggested the Part-A, Part-B, Part-C, and Part-D exams like SA-1, SA-2, FA-1, FA-2, FA-3, FA-4 along with Assignments.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter
Host by is-Programmer.com | Power by Chito 1.3.3 beta | © 2007 LinuxGem | Design by Matthew "Agent Spork" McGee