Max Sum

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>
#include<string>
using namespace std;
int main(){
	int m,n;
	cin>>n;
	for(int i=1;i<=n;i++){
		cin>>m;
		int a[m];
		for(int j=0;j<m;j++){
			cin>>a[j];
		}
		int la=0,lb=0,max=0,sum=0;
		for(int j=0;j<m;j++)
		{
			sum=a[j];
			for(int k=j+1;k<m;k++){
				sum=sum+a[k];
				if(max<sum){
					la=j;
					lb=k;
					max=sum;
				}
			}
		}
		cout<<"Case "<<i<<":"<<endl;
		cout<<max<<" "<<la<<" "<<lb<<endl;
		if(i<n)
		cout<<endl;
	}
	return 0;
}

後來搜索了網上的博客,發現用動態規劃可以大大節約時間,之前的計算複雜度爲n^3,動態規劃可以大大降低暴力搜索帶來的計算開銷,因爲用暴力搜索很多次計算都是無效的。

#include<iostream>
#include<string>
#include<algorithm>
#include<string.h>
using namespace std;
int main(){
	int m,n;
	cin>>n;
	for(int i=1;i<=n;i++){
		cin>>m;
		int a[m],b[m];
		int la=0,lb=0,max1=-1001,sum=0;
		memset(b,0,sizeof(b));
		for(int j=1;j<=m;j++){
			cin>>a[j];
			b[j]=max(a[j],b[j-1]+a[j]);
		//	cout<<b[j]<<" ";
			if(max1<b[j])
			{
				lb=j;
				max1=b[j];
			}
		}
	//	cout<<endl;
		for(int j=lb;j>0;j--)
		{
			sum=sum+a[j];
			if(sum==max1)
			{
				la=j;
				;
			}
		}	
		cout<<"Case "<<i<<":"<<endl;
		cout<<max1<<" "<<la<<" "<<lb<<endl;
		if(i<n)
		cout<<endl;
	}
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章