cjweffort

博客园 首页 联系 订阅 管理

题意要求最大子序列和,一道很经典的题目,可以用贪心算法解之~~

// 1007. Maximum Subsequence Sum.cpp: 主项目文件。

#include "stdafx.h"
#include <cstdio>

int main()
{
    int n;
	while(~scanf("%d",&n)){
		int leftTemp,left,right,curSum=0,maxSum=-1;
		int first,end;
		bool tag=false;
		for(int i=0;i<n;i++){
			int temp;
			scanf("%d",&temp);
			if(i==0){
				first=temp;
				leftTemp=temp;
			}
			if(i==n-1)
				end=temp;
			if(temp>=0)
				tag=true;
			if(curSum<0){
				leftTemp=temp;
				curSum=temp;
			}
			else{
				curSum+=temp;
			}
			if(curSum>maxSum){
				maxSum=curSum;
				left=leftTemp;
				right=temp;
			}
		}
		if(tag)
			printf("%d %d %d\n",maxSum,left,right);
		else
			printf("0 %d %d\n",first,end);
	}
    return 0;
}


posted on 2013-03-10 08:48  cjweffort  阅读(149)  评论(0编辑  收藏  举报