您的位置:首页 > 其它

HDOJ1003 Max Sum(脑洞)

2015-09-25 23:10 423 查看
题目链接:

t组样例,每组样例开始是n,后n个数字组成一个数组。问你连续的哪些数之和最大。

每读入一个数字加到tmp上,代表当前数之和,若tmp比ans大则更新ans,同时更新起始和结束的点。若tmp为负则更新起点为j+1,

且tmp重置为0。保证了ans能取得最大。

AC代码:

#include "iostream"
#include "cstdio"
#include "cstring"
#include "algorithm"
using namespace std;
const int MAXN = 1e5 + 5;
const int INF = 0x3f3f3f3f;
int n, a[MAXN];
int main(int argc, char const *argv[])
{
	int t;
	scanf("%d", &t);
	for(int cas = 1; cas <= t; ++cas) {
		scanf("%d", &n);
		int ans = -INF, tmp = 0, x, st, ed;
		for(int i = 1, j = 1; j <= n; ++j) {
			scanf("%d", &x);
			tmp += x;
			if(tmp > ans) {
				ans = tmp;
				st = i;
				ed = j;
			}
			if(tmp < 0) {
				i = j + 1;
				tmp = 0;
			}
		}
		printf("Case %d:\n", cas);
		printf("%d %d %d\n", ans, st, ed);
		if(cas != t) printf("\n");
	}
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: