PAT A 1007

来源:互联网 发布:java伪静态页面 编辑:程序博客网 时间:2024/06/18 09:01

• 题目

求n个数的最大子序列和,以及这个子序列开始和结束的数。

如果套上一般的最大子序列函数,连续WA,都在于“这个子序列开始和结束的数”。
这告诉我们,要认真读题,思路对的话Wa一般都是边界和特殊情况,多调试。
题目中对特殊情况的解释:
In case that the maximum subsequence is not unique, output the one with the smallest indices i and j (as shown by the sample case). If all the K numbers are negative, then its maximum sum is defined to be 0, and you are supposed to output the first and the last numbers of the whole sequence.
具体实现,使得maxsum函数臃肿了一些。

• I/O

Sample Input:
10
-10 1 2 3 4 -5 -23 3 7 -21
Sample Output:
10 1 4

• 算法

<最大子序列和>
这道题目名字直接告诉了算法。可以直接记模板,但还是写一个比较深刻。
穷举的方法可以通过来回比较缩短时间到O(n2),但有时候最大子序列和可能会作为一些更为复杂的问题的子问题,光是n平方是不够的,利用类似DP的思路可以得到O(n)和常量空间的算法。
○ 对于每一个输入,不依赖于后面输入,立即计算其结果并保存,然后与后续输入进行比较,若和变大,产生更新。若和总是变小,丢弃之前的输入
运用对a[i]的一次穷举(for),维护curSum和maxSum,线性时间复杂度就可以求出最大和。
对特殊情况的处理,对maxsum函数的改动已经作突出显示。
考虑的特殊情况:
○ -1 -2 -4(全是负数)
○ -1 0 -2 -4(全是非整数)
○ 0 0 0(全是0) 这种情况其实已经无所谓end的位置了,但为了严谨还是要考虑。

• 代码

#include<cstdio>#include<cstring>void maxsublinear(int a[10010], int n){    int i;    int curSum = 0; /* 当前序列和 */    int maxSum = 0; /* 最大序列和 */    int begin = 0, end = 0;    int out_begin = 0, out_end = 0;    int allNegative = 1;    /* 开始循环求子序列和 */    for (i = 0; i < n; i++)    {        curSum = curSum + a[i];        if(a[i] == 0 && allNegative)        {   out_begin = i;            out_end = i;        }        if(a[i]>=0) allNegative = 0;        /* 与最大子序列和比较,更新最大子序列和 */        if (curSum > maxSum)        {            maxSum = curSum;            end = i;            out_begin = begin;            out_end = end;        }        /* 动态规划部分,舍弃当前和为负的子序列 */        if (curSum < 0)        {            curSum = 0;            begin = i + 1 >= n ? i : i + 1;        }    }    //situation: all the numbers are negative    if(allNegative)    {   out_end = n-1;        out_begin = 0;    }    printf("%d %d %d",maxSum,a[out_begin],a[out_end]);}int main(){   int n;    int seq[10010];    scanf("%d",&n);    for(int i = 0; i<n; i++)        scanf("%d", &seq[i]);    maxsublinear(seq, n);    return 0;}
0 0
原创粉丝点击