HDOJ 1024 Max Sum Plus

Source: Internet
Author: User

Idea: the dynamic planning method is used to solve the sum of the maximum m sub-segments. Because the data volume of this question is large, two-dimensional dp programming is not available and optimization is considered.
Using a temp [1000005] to store the largest sum of the I sub-segments of the first j elements, dp [j] = max (dp [J-1] + s [j], temp [J-1] + s [j]) represents the maximum child segment and

Note: scanf is widely used for input data.

Code:
# Include <iostream>
# Include <algorithm>
# Include <map>
# Include <cstdio>
# Include <string>
# Include <cstring>
Using namespace std;
Int s [1000005];
Int dp [1000005];
Int temp [1000005];
Void DP (int m, int n ){
Int I, j, k;
Int max;
Memset (dp, 0, sizeof (dp ));
Memset (temp, 0, sizeof (temp ));
For (I = 1; I <= m; I ++) {// use a for loop Traversal
Max =-999999999; // note that the value of max here must be an infinitely small value, which is initialized respectively when the maximum size of the I sub-segment is obtained.
For (j = I; j <= n; j ++ ){
Dp [j] = (dp [J-1] + s [j])> (temp [J-1] + s [j])? (Dp [J-1] + s [j]): (temp [J-1] + s [j]);
Temp [J-1] = max; // here temp [J-1] is used to store the element I sub-segment maximum of the previous J-1, note that it is not temp [j] Because max <dp [j] has not been determined;
If (max <dp [j])
Max = dp [j]; // update max
}
}
Cout <max <endl;
}
Int main (){
Int I, j;
Int n, m;
While (scanf ("% d", & m, & n )! = EOF ){
For (I = 1; I <= n; I ++)
Scanf ("% d", & s [I]);
DP (m, n );
}
Return 0;
}
Author: cgl1079743846

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.