HDU1003

输入的第一行包含整数T(1 <= T <= 20),表示测试用例的数量。然后是T行,每行以数字N(1 <= N <= 100000)开始,然后是N个整数(所有整数都在-1000和1000之间)。

对于每个测试用例,您应输出两行。第一行是“Case#:”,#表示测试用例的编号。第二行包含三个整数,序列中的最大和,子序列的起始位置,子序列的结束位置。如果有多个结果,则输出第一个结果。在两个案例之间输出一个空行。

2

5 6 -1 5 4 -7

7 0 6 -1 1 -6 7 -5

Case 1: 14 1 4

Case 2: 7 1 6

我的代码

#define maxn 100010
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int a[maxn];
int main()
{
	int n;
	scanf("%d",&n);
	for(int k=1;k<=n;++k)
	{
		int count,start,end,max_sum=-10000;
		scanf("%d",&count);
		memset(a,0,sizeof(a));
		printf("Case %d:\n",k); 
		for(int i=0;i<count;++i)
			scanf("%d",&a[i]);
		for(int j=0;j<count;++j)
		{
			int temp=0;
			for(int i=j;i<count;++i)
			{
				temp+=a[i];
				if(temp>max_sum)
				{
					start=j+1;
					end=i+1;
					max_sum=temp;
				}	
			} 
		}
		printf("%d %d %d\n",max_sum,start,end);
		if(k!=n)
			printf("\n");
	}
	return 0;
} 

题目不难,但是嵌套两个循环会Time Limit Exceeded,最好的办法是输入一个数字计算一次,以下是最优O(n)代码,太吊了~

#include<stdio.h>
int main()
{
	int n,count,start,end,max,temp;
	int thisstart,thismax;
	scanf("%d",&n);
	for(int id=1;id<=n;++id)
	{
		scanf("%d",&count);
		scanf("%d",&max);
		thisstart=start=end=0;
		thismax = max;
		if(thismax<0)
		{
			thismax=0;
			thisstart=1;
		}
		for(int i=1;i<count;++i)
		{
			scanf("%d",&temp);
			thismax+=temp;
			if(thismax>max)
			{
				max=thismax;
				start=thisstart;
				end=i;
			}
			if(thismax<0)
			{
				thisstart=i+1;
				thismax=0;
			}
		}
		printf("Case %d:\n%d %d %d\n",id,max,start+1,end+1);
		if(id!=n)
			printf("\n");
	}
	return 0;
} 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值