2017年5月校賽賽前練習 最大連續區間和

Problem A: 最大連續區間和

Time Limit: 1 Sec  Memory Limit: 32 MB
Submit: 43  Solved: 2
[Submit][Status]

Description

你的任務是找出一串數字中,哪一些連續數字之和最大,並輸出這個和。

例如:輸入的一串數字爲“-1 2 -3 4 2 -5 6 -5”,你需要輸出“7”(在該輸入中,和最大的一些連續數字爲“4 2 -5 6”)。

Input

第一行爲測試用例的組數。

每組輸入包括兩行,第一行爲一串數的個數n (n<=10^5)。

隨後一行爲該串數字,每兩個數中間會用空格隔開。(題目保證每個數的絕對值小於10^9)

Output

對每一組測試用例,輸出最大和是多少

Sample Input

23-1 -2 -38-1 2 -3 4 2 -5 6 -5

Sample Output

-17

HINT

[Submit][Status]
思路:
方法一:分治法
方法二:maxn爲最大連續數字之和,temp爲當前連續數字之和
方法三:用a[i]表示以第i個數字結尾的最大連續數字和,a數組中最大的數即爲結果。
注意:雖然每個數字在int表示範圍內,但運算後(相加)的數字可能大於int

歡迎交流:
下面的方法二是正確的,我寫的方法三有點點錯誤,希望大神給菜鳥我指出,萬分感謝

方法二:
#include<cstdio>
#include<algorithm>
#include<string.h>
using namespace std;

//const int MAXN = 100000 + 5;
typedef  long long ll;

int main()
{

	int t;
	scanf("%d", &t);
	while (t--)
	{
		int n;
		scanf("%d", &n);
		ll maxn=0, temp=0;//maxn爲最大連續數字之和,temp爲當前連續數字之和
		for (int i = 0; i <n; i++)
		{

			int c;
			scanf("%d", &c);

			if (i == 0) 
			{ 
				maxn = c; 
				
				if (c < 0)temp = 0;
				else temp = c; 
			}
			else
			{
				temp += c;
				if (temp>maxn)maxn = temp;
				else if (temp < 0)temp = 0;//假設temp爲前i個數字和,因爲temp爲0,那麼前i+1個的最大數字和一定是第i+1個數字
			}

		}
		printf("%lld\n", maxn);
	}

	return 0;
}



方法三:我寫的方法三有點點錯誤,希望大神給菜鳥我指出,萬分感謝
#include<cstdio>
#include<algorithm>
#include<string.h>
using namespace std;

typedef long long ll;

const int MAXN = 100000 + 5;
ll r[MAXN];//用r[i]表示以第i個數字結尾的最大連續數字和,r數組中最大的數即爲結果。

bool cmp(int a, int b)
{
	return a > b;
}

int main()
{
	
	int t;
	scanf("%d", &t);
	while (t--)
	{
		memset(r, 0, sizeof(r));
		int n;
		scanf("%d",&n);
		for (int i = 0; i <n; i++)
		{
			
			ll c;
			scanf("%lld",&c);
			if (i==0) r[i] = c;
			else 
			 r[i] =max(c,c+r[i-1]);
		}
		sort(r,r+n,cmp);
		printf("%lld\n",r[0]);
	}
	


	return 0;
}






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