• 【u123】最大子段和


    Time Limit: 1 second
    Memory Limit: 128 MB
    【问题描述】

    给出一段序列,选出其中连续且非空的一段使得这段和最大。

    【输入格式】

    输入文件maxsum1.in的第一行是一个正整数N,表示了序列的长度。 第2行包含N个绝对值不大于10000的整数A[i],描述了这段序列。
    【输出格式】

    输入文件maxsum1.out仅包括1个正整数,为最大的子段和是多少。
    【数据规模】

    对于40%的数据,有N ≤ 2000。 对于100%的数据,有N ≤ 200000。
    Sample Input1
    7
    2 -4 3 -1 2 -4 3
    Sample Output1
    4

    【题目链接】:http://noi.qz5z.com/viewtask.asp?id=u123

    【题解】

    设f[i]表示当i出现在最后的答案里且为最后一个数字时能够获取的最大和;
    则有两种可能,只有这个数字本事作为答案,或者和之前连续的一段一起作为答案;则在a[i]和a[i]+f[i-1]之间取较大值;

    【完整代码】

    #include <cstdio>
    #include <cstdlib>
    #include <cmath>
    #include <set>
    #include <map>
    #include <iostream>
    #include <algorithm>
    #include <cstring>
    #include <queue>
    #include <vector>
    #include <stack>
    #include <string>
    using namespace std;
    #define lson l,m,rt<<1
    #define rson m+1,r,rt<<1|1
    #define LL long long
    #define rep1(i,a,b) for (int i = a;i <= b;i++)
    #define rep2(i,a,b) for (int i = a;i >= b;i--)
    #define mp make_pair
    #define pb push_back
    #define fi first
    #define se second
    
    typedef pair<int,int> pii;
    typedef pair<LL,LL> pll;
    
    void rel(LL &r)
    {
        r = 0;
        char t = getchar();
        while (!isdigit(t) && t!='-') t = getchar();
        LL sign = 1;
        if (t == '-')sign = -1;
        while (!isdigit(t)) t = getchar();
        while (isdigit(t)) r = r * 10 + t - '0', t = getchar();
        r = r*sign;
    }
    
    void rei(int &r)
    {
        r = 0;
        char t = getchar();
        while (!isdigit(t)&&t!='-') t = getchar();
        int sign = 1;
        if (t == '-')sign = -1;
        while (!isdigit(t)) t = getchar();
        while (isdigit(t)) r = r * 10 + t - '0', t = getchar();
        r = r*sign;
    }
    
    const int MAXN = 2e5+100;
    const int dx[9] = {0,1,-1,0,0,-1,-1,1,1};
    const int dy[9] = {0,0,0,-1,1,-1,1,-1,1};
    const double pi = acos(-1.0);
    
    int n;
    int f[MAXN],a[MAXN];
    
    int main()
    {
        //freopen("D:\rush.txt","r",stdin);
        rei(n);
        rep1(i,1,n)
            rei(a[i]);
        rep1(i,1,n)
            f[i] = max(a[i],f[i-1]+a[i]);
        int ans = f[1];
        rep1(i,2,n)
            ans = max(ans,f[i]);
        printf("%d
    ",ans);
        return 0;
    }
  • 相关阅读:
    开源收集
    理财
    MSSQL
    MAC-Python
    设计模式
    数据分析
    wkhtmltopdf是一个使用webkit网页渲染引擎开发的用来将 html转成 pdf的工具
    ETL
    MQ
    Java 资源
  • 原文地址:https://www.cnblogs.com/AWCXV/p/7626908.html
Copyright © 2020-2023  润新知