UVa 507 - Jill Rides Again

24 篇文章 0 订阅

最大连续和问题,注意其还有一要求是需要路径最长,即:当其和相同时,取路程最大的一段路的起点和终点,也就是说如果其和相同但其路径较短则不必更新先前保存的起点与终点位置。

代码如下:

#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<ctime>

using namespace std;

int main()
{
#ifdef test
    freopen("in.txt", "r", stdin);
#endif
    int t, n, a[20005], ct = 0;
    scanf("%d", &t);
    while(t--)
    {
        scanf("%d", &n);
        int sum = 0, max = -100000;
        int start, end, st = 0;
        for(int j = 0; j < n - 1; j++)
        {
            scanf("%d", &a[j]);
            sum = sum + a[j];
            if(sum > max)
            {
                max = sum;
                end = j + 1;
                start = st;
            }
            if(sum == max && end - start < j - st) // 和相同时,判断其路径是否比先前的路径长
            {
                max = sum;
                end = j + 1;
                start = st;
            }
            if(sum < 0)
            {
                sum = 0;
                st = j + 1;
            }
        }
        if(max < 0)
            printf("Route %d has no nice parts\n", ++ct);
        else
            printf("The nicest part of route %d is between stops %d and %d\n", ++ct, start + 1, end + 1);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值