zoukankan      html  css  js  c++  java
  • 最大子序和——队列

    题目描述

    输入一个长度为n的整数序列,从中找出一段不超过M的连续子序列,使得整个序列的和最大。
    例如 1,-3,5,1,-2,3
    当m=4时,S=5+1-2+3=7
    当m=2或m=3时,S=5+1=6

    输入

    第一行两个数n,m
    第二行有n个数,要求在n个数找到最大子序和

    输出

    一个数,数出他们的最大子序和

    样例输入

    6 4
    1 -3 5 1 -2 3
    

    样例输出

    7

    提示

    30%满足 n,m<=100
    50%满足 n,m<=3000
    100%满足n,m<=300000
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%分界线
    题目数据说明这个题用dp或许不太可取,况且小伙伴试过之后说不能过,那么说明这个题有更好的方法来解决这个问题
    可以用单调队列我写了好久没有出答案 还可以模拟单调队列
    还有就是这个题在acwing上面有原题并且yxc大佬讲的很好我不是托
    附上链接 https://www.acwing.com/problem/content/137/
    而且我下面的代码也是向yxc大佬学的

    #pragma GCC optimize("Ofast,unroll-loops,no-stack-protector,fast-math")
    #pragma GCC optimize("Ofast")
    #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
    #pragma comment(linker, "/stack:200000000")
    #pragma GCC optimize (2)
    #pragma G++ optimize (2)
    #include <bits/stdc++.h>
    #include <algorithm>
    #include <map>
    #include <queue>
    #include <set>
    #include <stack>
    #include <string>
    #include <vector>
    using namespace std;
    #define wuyt main
    typedef long long ll;
    #define HEAP(...) priority_queue<__VA_ARGS__ >
    #define heap(...) priority_queue<__VA_ARGS__,vector<__VA_ARGS__ >,greater<__VA_ARGS__ > >
    template<class T> inline T min(T &x,const T &y){return x>y?y:x;}
    template<class T> inline T max(T &x,const T &y){return x<y?y:x;}
    //#define getchar()(p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1 << 21, stdin), p1 == p2) ? EOF : *p1++)
    //char buf[(1 << 21) + 1], *p1 = buf, *p2 = buf;
    ll read(){ll c = getchar(),Nig = 1,x = 0;while(!isdigit(c) && c!='-')c = getchar();
    if(c == '-')Nig = -1,c = getchar();
    while(isdigit(c))x = ((x<<1) + (x<<3)) + (c^'0'),c = getchar();
    return Nig*x;}
    #define read read()
    const ll inf = 1e15;
    const int maxn = 3e5 + 10;
    const int mod = 1e9 + 7;
    #define start int wuyt()
    #define end return 0
    ll num[maxn],ans;
    ll n,m;
    ll a[maxn],s[maxn];
    start{
        n=read,m=read;
        s[0]=0;
        for(int i=1;i<=n;i++)
        {
            s[i]=read;
            s[i]+=s[i-1];
        }
        int left=0,right=0;
        ll res=INT_MIN;
        for(int i=1;i<=n;i++)
        {
            if(i-a[left]>m) left++;
            res=max(res,s[i]-s[a[left]]);
            while(left<=right&&s[a[right]]>=s[i]) right--;
            a[++right]=i;
        }
        cout<<res;
    	end;
    }
    
    
  • 相关阅读:
    liunx 用户切换 su sudo
    tomcat 虚拟目录
    如何用vue封装一个防用户删除的平铺页面的水印组件
    webpack入门学习手记(一)
    理解跨域及常用解决方案
    封装一个优雅的element ui表格组件
    使用Koa.js离不开这十个中间件
    深入理解let和var的区别
    编辑器IDE之VSCode
    WTF!! Vue数组splice方法无法正常工作
  • 原文地址:https://www.cnblogs.com/PushyTao/p/13144213.html
Copyright © 2011-2022 走看看