51 nod 1049 最大子段和 (简单dp)
生活随笔
收集整理的這篇文章主要介紹了
51 nod 1049 最大子段和 (简单dp)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?
?
1049?最大子段和?
基準時間限制:1?秒 空間限制:131072?KB 分值:?0?難度:基礎題
N個整數組成的序列a[1],a[2],a[3],…,a[n],求該序列如a[i]+a[i+1]+…+a[j]的連續子段和的最大值。當所給的整數均為負數時和為0。
例如:-2,11,-4,13,-5,-2,和最大的子段為:11,-4,13。和為20。
Input
第1行:整數序列的長度N(2?<=?N?<=?50000) 第2?-?N?+?1行:N個整數(-10^9?<=?A[i]?<=?10^9)Output
輸出最大子段和。Input示例
6 -2 11 -4 13 -5 -2Output示例
20解題思路:
我們可以創建一個數組dp,dp[i]來保存以a[i]結尾的最大字段和。
那么就有,dp[i]自然就是兩個之中最大的那個。
AC代碼:
#include <stdio.h> #include <iostream> #include <stdlib.h> #include <string.h> #include <math.h> #include <algorithm> #include <map> #include <stack> #include <queue> using namespace std; long long a[50000]; long long dp[50005]; int main() {long long n;scanf("%lld",&n);memset(dp,0,sizeof(dp));for(int i=1;i<=n;i++)scanf("%lld",&a[i]);for(int i=1;i<=n;i++)dp[i]=max(a[i],dp[i-1]+a[i]);//剛開始以a[i]結尾的就是最大的,在往前面找,前面如果有就是前面的最大的加上a[i];long long mmax=dp[1];for(int i=1;i<=n;i++){if(mmax<dp[i])mmax=dp[i];}printf("%lld\n",mmax);//注意數據范圍return 0; }對于dp題目,最難的就是找的狀態轉移方程....
我覺得它和貪心不一樣的地方就是貪心沒有重疊的子問題,但是動態規劃有重疊的子問題,所以才需要dp來降時間。?
轉載于:https://www.cnblogs.com/zut-syp/p/10543742.html
總結
以上是生活随笔為你收集整理的51 nod 1049 最大子段和 (简单dp)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Go goroutine
- 下一篇: django入门三(视图)