PAT 1007. Maximum Subsequence Sum (25)

来源:互联网 发布:空间数据的差值 编辑:程序博客网 时间:2024/06/02 12:36

1007. Maximum Subsequence Sum (25)

时间限制
400 ms
内存限制
32000 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

Given a sequence of K integers { N1, N2, ..., NK }. A continuous subsequence is defined to be { Ni, Ni+1, ..., Nj } where 1 <= i <= j <= K. The Maximum Subsequence is the continuous subsequence which has the largest sum of its elements. For example, given sequence { -2, 11, -4, 13, -5, -2 }, its maximum subsequence is { 11, -4, 13 } with the largest sum being 20.

Now you are supposed to find the largest sum, together with the first and the last numbers of the maximum subsequence.

Input Specification:

Each input file contains one test case. Each case occupies two lines. The first line contains a positive integer K (<= 10000). The second line contains K numbers, separated by a space.

Output Specification:

For each test case, output in one line the largest sum, together with the first and the last numbers of the maximum subsequence. The numbers must be separated by one space, but there must be no extra space at the end of a line. 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.

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

提交代码

解法一:一次扫描即可。

#include<stdio.h>const int MAX=10001;int INF=-100000; int r[MAX];int main(){int n,i,j,k,sum;//freopen("G:\\in.txt","r",stdin);while(scanf("%d",&n)!=EOF){int ans=INF,begin,end;//每次开始时初始化。ans不要设置为0,设置为负无穷。。。不然有一个用例错误,只能得22分。。。for(i=0;i<n;i++)scanf("%d",&r[i]);bool isNegative=1;for(i=0;i<n;i++){if(r[i]>=0){  //非负数是大于等于0。。。别掉了等于。。。isNegative=0;break;}}if(isNegative==1){printf("0 %d %d",r[0],r[n-1]);printf("\n");}else{i=j=0; begin=end=sum=0; //i,j标记当前扫描的子串的起点和终点。for(k=0;k<n;k++){sum=sum+r[k];  //第一个为负数,必然跳过。。if(sum<0&&k+1<n){     //如果sum小于0,接下来重新开始扫描。因为和小于0的子串不可能 作为 前缀。i=j=k+1;sum=0;}else{      //只有和不小于0时,才可能会修改begin,end,ans的值。因为若不全是负数,最大串的和必然不小于0。。j=k;if(sum>ans){ans=sum;begin=r[i];end=r[j];}}}printf("%d %d %d\n",ans,begin,end);}}return 0;}



解法2:二重循环,暴力扫描。

#include<stdio.h>const int MAX=10001; int r[MAX];int ans=-10000,begin,end;//ans不要设置为0,设置为负无穷。。。不然有一个用例错误,只能得22分。。。int main(){int n,i,j,k,tmp;//freopen("G:\\in.txt","r",stdin);while(scanf("%d",&n)!=EOF){if(n==0)continue;for(i=0;i<n;i++)scanf("%d",&r[i]);bool isNegative=1;for(i=0;i<n;i++){if(r[i]>=0){  //非负数是大于等于0。。。别掉了等于。。。isNegative=0;break;}}if(isNegative==1){printf("0 %d %d",r[0],r[n-1]);printf("\n");}else{for(j=0;j<n;j++){ //暴力扫描tmp=0;   //每轮开始时tmp置为0,放上上面一行,谬以千里。。。for(k=0;j+k<n;k++){tmp=r[j+k]+tmp; //tmp保存累加和if(tmp>ans){ans=tmp;begin=r[j];end=r[j+k];}}}printf("%d %d %d\n",ans,begin,end);}}return 0;}




 

0 0
原创粉丝点击