杭电60题--part 1 HDU1003 Max Sum(DP 动态规划)
最近想學DP,鍛煉思維,記錄一下自己踩到的坑,來寫一波詳細的結題報告,持續更新。
題目鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=1003
?
Problem Description
Given a sequence a[1],a[2],a[3]......a[n], your job is to calculate the max sum of a sub-sequence. For example, given (6,-1,5,4,-7), the max sum in this sequence is 6 + (-1) + 5 + 4 = 14.
Input
The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line starts with a number N(1<=N<=100000), then N integers followed(all the integers are between -1000 and 1000).
Output
For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line contains three integers, the Max Sum in the sequence, the start position of the sub-sequence, the end position of the sub-sequence. If there are more than one result, output the first one. Output a blank line between two cases.
Sample Input
2 5 6 -1 5 4 -7 7 0 6 -1 1 -6 7 -5
Sample Output
Case 1: 14 1 4 Case 2: 7 1 6
Author
Ignatius.L
Recommend
We have carefully selected several similar problems for you:??1069?2084?1058?1421?1024?
這一個題是一個基本題型,先分析數據這點很重要,剛剛踩坑,這里每個ai大于-1000,小于1000,那么min為-1e3*1e5,也就是說求和后最小值最大值為1e8量級,那么比較時最大最小值一定設置比這個量級大或在這個量級最大,而我沒考慮到如果全為負數時的情況。
開始說題目,這個題目找最大子串,對于任意一個元素,它有兩種可能性,做上個子串的最后一個字符,作以自己開頭的子串的第一個字符,我們這里不考慮當前字符后續字符,因為DP子問題無后效性,那么兩種狀態到了,我們要找出兩種狀態分支的條件,如果一個元素跟著前面的大哥混沒前途,那就不跟他混了,自立山頭,不前面序列的和都小于0,不如自己做開頭。即可寫出狀態轉移方程。,這里問什么沒寫等于0呢,因為題目的要求是找最靠前的左端點,所以這等于號要放到上面,但是我們怎么存儲端點呢?一樣的狀態轉移,我跟前面的老大哥們混,我的頭頭肯定是前面的老大哥,所以那我的老大哥也是這個子序列的第一個,如果這個小團伙沒落了,我自立山頭,那么后來的人的大哥肯定會是我,所以就有了狀態轉移方程,再開一維,也可以再開一個數組,我不太建議跑好幾遍循環的方法,能簡化就簡化。
if(dp[i-1][1]<0||i==1) //i==1細節操作,自己想一下 {dp[i][0]=i;dp[i][1]=a[i]; } else {dp[i][0]=dp[i-1][0];dp[i][1]=dp[i-1][1]+a[i]; }應該沒什么要注意了,還有就是 初始化,這是多組輸入。
總結
以上是生活随笔為你收集整理的杭电60题--part 1 HDU1003 Max Sum(DP 动态规划)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 省电就是赚钱 RTX 4070 Ti比A
- 下一篇: 图论--BFS总结