1. 程式人生 > >【 OJ 】 HDOJ1003 18年10月25日16:41 [ 4 ]

【 OJ 】 HDOJ1003 18年10月25日16:41 [ 4 ]

難受想哭,檢查了N次,但是還是WA,真的難受,求有沒有大佬帶打副本HDOJ的,感覺打副本蠻有意思的,但是一直卡在這提交上,好煩.........嗚嗚,有沒有大神指教下到底

/*
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
10 -5 -6 3 2 1 -7 6 3 -10 8

答案:9 7 8
1
10 9 -6 -7 3 2 1 -1 -1 -1 9
答案:12 4 10
*/

# include <iostream>
# define Num 100001
using namespace std;

int a[Num];
void out(int time,int sum,int s,int e) {
	cout << "Case " << time << ":" << endl;
	cout << sum << " " << s << " " << e << endl;
}
int addMax(int*a,int n, int *startIndex1, int*endIndex1) {
	*startIndex1 = *endIndex1 = 0;//重置0位置
	int sum = -999;
	int temp_Sum = 0;
	int tsindex, teindex;
	tsindex = teindex = 1;
	for (int i = 0; i < n; ++i) {
		temp_Sum = temp_Sum + a[i];//加上當前數字
		if (temp_Sum >= 0) {//有希望
			teindex = i+1;//如果有上升趨勢那麼臨時end上去
			if (temp_Sum > sum) {
				sum = temp_Sum;
				*startIndex1 = tsindex;
				*endIndex1 = teindex;
			}
		}
		else {//已經負數沒上升趨勢了
			tsindex = i + 2;//當前座標為 i 但是在1為開頭是 i+1 所以下一個是 i+2
			teindex =tsindex;//當前座標 i 一定是大負數
			temp_Sum = 0;
		}
	}
	return sum;
}
int main(void) {
	int n;//次數
	int N;//每次個數
	int startIndex=1, endIndex=1;
	int sum = 0;
	cin >> n;//次數
	if (n >= 1 && n <= 20) {
		for (int j = 0; j < n; ++j) {
			cin >> N;//確認錄入陣列個數
			if (N >= Num)//此行加上就不會出先執行時錯誤(真的煩)
				return 0;
			for (int i = 0; i < N; ++i) {
				cin >> a[i];
			}//對陣列進行輸入
			//對陣列進行動態規劃統計最大值,起始位置和終止位置
			sum = addMax(a, N, &startIndex, &endIndex);
			out(j + 1, sum, startIndex, endIndex);
			if (j != n - 1)
				cout << endl;
		}
	}
	else
		return 0;
	system("pause");
	return 0;
}

哪裡錯了.......