数学考试 【每日一题】3月27日题目精讲 前缀和、动态规划

https://ac.nowcoder.com/acm/problem/15553

因为长度已知,最暴力的办法肯定是直接枚举两个子区间的起点,然后求和。

可以用前缀和来进行优化,sum[i]=sum[i-1]+a[i],则区间[l,r]的和就是sum[r]-sum[l-1],这样优化之后就不用遍历求和了直接算就好,时间复杂度变为O(n的平方),两个方向分别前行,遍历一遍以后求出两个dp数组,最后总的遍历找出相加的最大值。

注意ans一定要无限小,要不就卡83%的数据,亲测。。。。

#include <iostream>
#include <bitset>
#include <algorithm>
#include <cmath>
#include <ctype.h>
#include <string>
#include <cstring>
#include <cstdio>
#include <set>
#include <cstdio>
#include <fstream>
#include <deque>
#include <vector>
#include <queue>
#include <map>
#include <stack>
#include <iomanip>
#define SIS std::ios::sync_with_stdio(false)
#define ll long long
#define INF 0x3f3f3f3f
const int mod = 1e9 + 7;
const double esp = 1e-5;
const double PI = 3.141592653589793238462643383279;
using namespace std;
const int N = 1e7 + 5;
const int maxn = 1 << 20;
ll powmod(ll a, ll b) { ll res = 1; a %= mod; while (b >= 0); for (; b; b >>= 1) { if (b & 1)res = res * a % mod; a = a * a % mod; }return res; }
ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; }
/*void chafen(int l, int r, int k) {//差分函数
    p[l] += k;
    p[r + 1] -= k;
}*/
/*********************************************************/
ll a[200005], b1[200005],b2[200005], dp1[200005], dp2[200005];
ll sum[200005];
int main() {
    int t;
    cin >> t;
    while (t--) {
        ll n, k;
        cin >> n >> k;
        memset(b1, -INF, sizeof(b1));
        memset(b2, -INF, sizeof(b2));
        ll ans = -1e18;
        for (ll i = 1; i <= n; i++)
            cin >> a[i];
        for (ll i = 1; i <= n; i++)
            sum[i] = sum[i - 1] + a[i];
        for (ll i = k; i <= n - k; i++)
            b1[i] = max(sum[i] - sum[i - k], b1[i - 1]);
        for (ll i = n-k+1; i >= k+1; i--)
            b2[i] = max(sum[i+k-1] - sum[i-1], b2[i + 1]);
        
        for (ll i = k; i <= n - k; i++)
            ans = max(b1[i] + b2[i+1],ans);
        cout << ans << endl;
    }
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章