杭電oj 1003




先看題目

Max Sum

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 190877    Accepted Submission(s): 44442


Problem Description
Given a sequence a[1],a[2],a[3]......a[n], your job is to calculate the max sum of a sub-sequence. For example, given (6,-1,5,4,-7), the max sum in this sequence is 6 + (-1) + 5 + 4 = 14.
 


Input
The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line starts with a number N(1<=N<=100000), then N integers followed(all the integers are between -1000 and 1000).
 


Output
For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line contains three integers, the Max Sum in the sequence, the start position of the sub-sequence, the end position of the sub-sequence. If there are more than one result, output the first one. Output a blank line between two cases.
 


Sample Input
2 5 6 -1 5 4 -7 7 0 6 -1 1 -6 7 -5
 
Sample Output
Case 1: 14 1 4 Case 2: 7 1 6


暴力肯定不行,一看就是動態規劃的題目。一維的動態規劃,有兩個點,如果遇到正數,加上去肯定是會變大的,對於一個數是這樣,對於很多個數的和也是一樣,第二點是如果前面的幾個數的和是負數,就要把起始位置改爲負數後的一點。再和前面最大的數比較,若後面有更大的數就改起始位置。

代碼如下


#include <iostream>
using namespace std;
int a[100000];


typedef struct
{
	int sum;
	int start;
	int end;
}result;

result dp(int count)
{
	int i;
	int max=-9999999;
	int k=1;
	result res;
	res.sum=0;
	i=1;
	while(i<=count)
	{
		res.sum+=a[i];
		if(res.sum>max)
		{
			max=res.sum;
			res.start=k;
			res.end=i;
		}
		if(res.sum<0)
		{
			res.sum=0;
			k=i+1;
		}
		
		i++;	
	} 
	res.sum=max;
	return res;
}

int main()
{
	result res;
	int i;
	int j=1;
	int number;
	int count;
	cin>>number;
	
	while(number)
	{
		cin>>count;
		for(i=1;i<=count;i++)
		{
			cin>>a[i];
		}
		res=dp(count);
		if(j!=1)  
           cout<<endl;  

		cout<<"Case "<<j<<":"<<endl;
		cout<<res.sum<<" "<<res.start<<" "<<res.end<<endl; 
		number--;	
		j++;
	}	
	return 0;
}


ac了


發佈了27 篇原創文章 · 獲贊 17 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章