507

求最大连续子序列和,还要求输出的是起点最靠前,并且最长的那个,

一开始没思路,只想到n2的了,看了一下别人的解题报告恍然大悟,自己开始没往那个方向想,只要不断一个一个记录更新就行了,

这个真应该快速就想到。。

有个讲的挺好的链接http://blog.sina.com.cn/s/blog_4bf7b6580100l3ju.html

//============================================================================
// Name        : 507.cpp
// Author      : 
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
//
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

int N, T, ans, ansl, ansr, l, r, t, n;
int a[20010];

int main() {
	freopen("a.txt", "r", stdin);
	scanf("%d", &N);
	for(int T = 1;T <= N;T++){
		memset(a, 0, sizeof(a));
		scanf("%d", &n);
		for(int i = 1;i < n;i++){
			scanf("%d", &a[i]);
		}
		t = 0;
		ansl = 0;
		ansr = 0;
		l = 1;
		r = 2;
		ans = 0;
		for(int i = 1;i < n;i++){
			t += a[i];
			if(t < 0){
				t = 0;
				l = i+1;
				r = i+2;
			}
			else{
				if(t > ans){
					ans = t;
					ansl = l;
					ansr = r;
				}
				else if(t == ans&&r-l > ansr-ansl){
					ansl = l;
					ansr = r;
				}
				r++;
			}
			//printf("%d %d %d\n", ans, l, r);
		}
		if(ans <= 0){
			printf("Route %d has no nice parts\n", T);
		}
		else{
			printf("The nicest part of route %d is between stops %d and %d\n", T, ansl, ansr);
		}
	}
	return 0;
}
posted @ 2011-05-31 21:48  KOKO's  阅读(429)  评论(0编辑  收藏  举报