hdu 1024(滚动数组的学习)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1024

学习了一下滚动数组,dp中经常卡内存,而利用滚动数组可以大大节省内存空间,不错哦。

View Code
 1 #include<iostream>
 2 #include<cstring>
 3 #include<algorithm>
 4 const int N=1000010;
 5 const int inf=1000000000;
 6 using namespace std;
 7 
 8 int a[N];
 9 int dp[N],pre[N];//dp[i][j]表示第j个数前组成i组的最大值;
10 //为了节省内存,可以用pre[j]来保存前一次求得的dp[j-1]的最大值,这样相当于数组在不断进行滚动
11 //最后输出temp即可;
12 
13 int main(){
14     int m,n;
15     while(scanf("%d%d",&m,&n)!=EOF){
16         for(int i=1;i<=n;i++){
17             scanf("%d",&a[i]);
18         }
19         memset(dp,0,sizeof(dp));
20         memset(pre,0,sizeof(pre));
21         int temp;
22         for(int i=1;i<=m;i++){
23             temp=-inf;
24             for(int j=i;j<=n;j++){
25                 dp[j]=max(dp[j-1]+a[j],pre[j-1]+a[j]);
26                 pre[j-1]=temp;
27                 temp=max(temp,dp[j]);
28             }
29         }
30         printf("%d\n",temp);
31     }
32     return 0;
33 }
原文地址:https://www.cnblogs.com/wally/p/2957061.html