zoukankan      html  css  js  c++  java
  • 3927Circular Sequence 思维题(求环形最大子列和)

    Given a sequence with n elements, if the last element is also adjacent to the first element of the sequence, the sequence is called “circular sequence”.
    Now, here comes a simple problem: given a circular sequence, you should find a segment of the sequence, such that it contains at least one element, and the sum of the elements is as large as possible. 

    输入

     

    Input may contain several test cases. The first line is a single integer t, the number of test cases below. Each test case is composed of two lines. The first line of each test case is a positive integer n (1<=n<=100000), denoting the number of elements in the circular sequence, and the second line has n integers; the absolute value of each integer is no more than 100000. 

    输出

     

    For each test case, output the maximum segment sum in a single line. 

    样例输入

    2
    2
    -1 -2
    3
    1 -2 3

    样例输出

    -1

    4

    不考虑环:直接找非循环子序列maxsum1;

    然后考虑循环:也就是两头相加情况,这是找非循环子序列minsum,把总和-minsum又得到一个maxsum2;

    但前提的要有负数存在,负数不存在的话就直接是总和了;

    否则就是max(maxsum1,maxsum2)

    #include<bits/stdc++.h>
    using namespace std;
    #define ll long long
    ll a[100005];
    int main()
    {
        int i,j,t,n;scanf("%d",&t);
        while(t--){
            scanf("%d",&n);
            ll maxx=-0x3f3f3f3f,minn=0x3f3f3f3f;
            ll sum=0,s=0;
            int f=0;
            for(i=0;i<n;i++){
                scanf("%I64d",&a[i]);
                if(a[i]>=0)f=1;
                s+=a[i];
                sum+=a[i];
                maxx=max(maxx,sum);
                if(sum<0)sum=0;
            }
            sum=0;
            for(i=0;i<n;i++){
                sum+=a[i];
                minn=min(minn,sum);
                if(sum>0)sum=0;
            }
            if(f==1)maxx=max(maxx,s-minn);
            printf("%I64d
    ",maxx);
        }
        return 0;
    }
    View Code
  • 相关阅读:
    pre 强制换行
    code标签和pre标签的定义
    angularJS绑定数据中对标签转义的处理二 与pre标签的使用
    angularJS绑定数据中对标签转义的处理
    html特殊字符
    js switch的使用 ng-switch的使用方法
    JS转换HTML转义符,防止javascript注入攻击,亲测可用
    MVC,MVP 和 MVVM 的图示 转自阮一峰先生网络日志
    AngularJs ngReadonly、ngSelected、ngDisabled
    你应该知道的jQuery技巧
  • 原文地址:https://www.cnblogs.com/ydw--/p/12515633.html
Copyright © 2011-2022 走看看