數學考試 【每日一題】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;
}

 

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