動態規劃01-HDU-1003

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


1,開始想法就是遍歷,

#include<iostream>
using namespace std;
long a[100000];
int main(){
	int T;
	int N;
	cin>>T;
	int i=1;
	while(i<=T){
		cin>>N;
		int j;
		for(j=0;j<N;j++){
			cin>>a[j];
		}
		long k,l,m=0,n=0,max=a[0];//k,對a數組遍歷;max保存目前最大值,m開始位置,n結束位置 
		for(k=0;k<N;k++){
			for(l=k;l<N;l++){
				long tempMax=0;
				int x;
			   for(x=k;x<=l;x++){
			    	tempMax+=a[x];
			   }
			    if(tempMax>max){
				 max=tempMax;
			   	 m=k;
				 n=l;
		   		}
			}
		}
		cout<<"Case "<<i<<":"<<endl;
		cout<<max<<" "<<++m<<" "<<++n<<endl;
		i++;
		if(i<=T) 
		cout<<endl;
	}
	return 0;
}

果然是時間超時。

2,查閱一些資料,對於最大子序列和的問題,已經找到的最大子序列的前部的和、後部的和都爲負數,這樣的纔是最大子序列。算法思想:遍歷數組a[],設定標誌位sum(爲遍歷數組的和,初始爲0),若sum值小於0,則將sum置爲0,重新求和。遍歷過程中對max、m、n進行保存。 

#include<iostream>
using namespace std;
long a[100009];
int main(){
	int T;
	int N;
	cin>>T;
	int i=1;
	while(i<=T){
		cin>>N;
		int j;
		for(j=0;j<N;j++){
			cin>>a[j];
		}
		long k,sum=0,m=0,n=0,max=a[0],p=0,q=0;//k,對a數組遍歷;max保存目前最大值,
		                                  //m目前最大值開始位置,n目前最大值結束位置, p臨時開始位置,q臨時結束位置
		for(k=0;k<N;k++){
				q=k;
			sum+=a[k];
			if(sum>max){
				max=sum;
				m=p;
				n=q;
			}
			if(sum<0){
				p=k+1;
				sum=0;
			}
		}
		cout<<"Case "<<i<<":"<<endl;
		cout<<max<<" "<<++m<<" "<<++n<<endl;
		i++;
		if(i<=T) 
		cout<<endl;
	}
	return 0;
}

時間複雜度n

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