#include <iostream> #include <cstdio> #include <cstring> const int maxn = 10050; struct node { int start,end; int sum; int value; }dp[maxn]; int main() { //std::cout << "Hello, World!" << std::endl; int K; scanf("%d",&K); for (int i = 0; i < K; ++i) { scanf("%d",&dp[i].value); } int maxSum=dp[0].value; dp[0].sum=dp[0].value; dp[0].start=dp[0].end=0; for (int i = 1; i < K; ++i) { if(dp[i].value+dp[i-1].sum>dp[i].value){ dp[i].sum=dp[i].value+dp[i-1].sum; dp[i].start=dp[i-1].start; dp[i].end=i; }else{ dp[i].sum=dp[i].value; dp[i].start=dp[i].end=i; } maxSum=maxSum>dp[i].sum?maxSum:dp[i].sum; } if(maxSum<0){ printf("0 %d %d ",dp[0].value,dp[K-1].value); }else{//注意输出下标最小的数值!!! printf("%d ",maxSum); for (int i = 0; i < K; ++i) { if(maxSum==dp[i].sum){ printf("%d %d ",dp[dp[i].start].value,dp[dp[i].end].value); break; } } } return 0; }
涉及动态规划,没学过打扰勿喷,个人理解就是下一节点保存上一节点的求和或者最下下标
ps.输出最小的首末数值