1. 程式人生 > >甲級PAT 1007 Maximum Subsequence Sum(給出部分坑的測試情況)

甲級PAT 1007 Maximum Subsequence Sum(給出部分坑的測試情況)

1007 Maximum Subsequence Sum (25)(25 分)

Given a sequence of K integers { N~1~, N~2~, ..., N~K~ }. A continuous subsequence is defined to be { N~i~, N~i+1~, ..., N~j~ } 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

 題目要求:

給出一個序列(可能包含負數、正數和0),找出這個序列中最大連續子序列和,輸出這個最大值,以及子序列的第一個數和最後一個數。

若序列中的所有數都是負數,則最大的子序列和為0,並輸出整個序列的第一個數和最後一個數。

解題思路:

這題肯定是一個動態規劃的題目。首先要找到狀態方程式,用dp[i]表示序列a中第i個數a[i]對應的最大連續子序列和,從下標0開始依次更新後面的dp[i]。初始值dp[0]=a[0]。從下標1開始,dp[i]只有兩種情況,dp[i]=a[i] (dp[i-1]+a[i] <= a[i])  或者dp[i]=dp[i-1]+a[i] (dp[i-1]+a[i] >a[i])。然後用start[i]來儲存序列每個數區域性最大連續子序列的起始下標。用sum來儲存當前所找到最大連續子序列的和,用l表示所找到最大連續子序列的第一個數下標,用r表示最大連續子序列的最後一個數下標。記得設初始值,start[0] = 0,sum=a[0],l=0,r=0。每次dp[i]>sum時更新sum,l,r的值。

完整程式碼:

#include<iostream>
using namespace std;
#define maxsize 10001

int a[maxsize];
int dp[maxsize];
int start[maxsize];

int main(){
	int K,i,l,r,sum,b;
	cin>>K;
	for(i=0;i<K;i++){
		cin>>a[i];
	}
	dp[0] = a[0];
	sum = a[0];
	start[0] = 0;
	l = 0;
	r = 0;
	for(i=1;i<K;i++){
		if(dp[i-1]+a[i]>a[i]){
			dp[i] = dp[i-1]+a[i];
			start[i] = start[i-1];
			if(dp[i]>sum){
				sum = dp[i];
				l = start[i];
				r = i;
			}
		}else if(dp[i-1]+a[i]==a[i]){
			start[i] = start[i-1];
			dp[i] = a[i];
			if(dp[i]>sum){
				sum = dp[i];
				l = start[i];
				r = i;
			}
		}else{
			dp[i] = a[i];
			start[i] = i;
			if(dp[i]>sum){
				sum = dp[i];
				l = start[i];
				r = i;
			}
		}
	}
	if(sum >= 0){
		cout<<sum<<" "<<a[l]<<" "<<a[r];
	}else{
		cout<<0<<" "<<a[0]<<" "<<a[K-1];
	}
	
	return 0;
} 

 坑的測試情況(之前自己寫程式碼不通過的例子):

1.

5

-9 9 -9 -9 9

2.

5

9 -9 -9 -9 9

3.

5

0 9 -9 0 9

4.

1

-5