제출 #1156809

#제출 시각아이디문제언어결과실행 시간메모리
1156809Esgeer수열 (APIO14_sequence)C++20
100 / 100
536 ms83272 KiB
#include <bits/stdc++.h>
#define int long long
#pragma GCC optimize("O3")
#define vi vector<int>
#define vb vector<bool>
#define F(i, s, e) for(int i = s; i < e; i++)
#define sp <<' '<<
#define pii pair<int, int>
#define fi first
#define se second
#define pb push_back
#define vvi vector<vi>
#define vpi vector<pii>
#define vvpi vector<vpi>
#define endl '\n'
 
const int mod = 1e9 + 7;
 
using namespace std;
 
const int N = 1e5+5;
const int inf = 1e15;

int dp[N],dp2[N];
int32_t origin[N][201];

struct Line {
    int a, b, from;
    int eval(int x) {
        return a*x+b;
    }
};

bool bad(Line &a, Line &b, Line &c) {
    if (b.a == c.a) {
        return b.b < c.b;
    }
    int u = (b.b - a.b);
    int v = (a.a - b.a);
    int z = (c.b-b.b);
    int t = (b.a-c.a);
    return u*t >= z*v;
}

void solve() {
    int n, k;
    cin >> n >> k;

    vi a(n+1, 0), p(n+1, 0);
    F(i, 0, n) cin >> a[i+1];
    F(i, 1, n+1) p[i] = p[i-1] + a[i];

    F(i, 0, n+1) F(j, 0, k+1) dp[i] = dp2[i] = -inf;

    F(j, 1, k+1) {
        deque<Line> q;
        if(j == 1) q.pb({0, 0, 0}); // base case
        F(i, 1, n+1) {
            if(q.size()) {
                int x = p[i];
                while(q.size() >= 2 && q[0].eval(x) < q[1].eval(x)) q.pop_front();
                dp[i] = q[0].eval(x) + p[i]*p[n] - p[i]*p[i];
                origin[i][j] = q[0].from;
            }

            // insert the new line
            Line nw = {p[i], -p[i]*p[n] + dp2[i], i};
            while(q.size() >= 2 && bad(q[q.size()-2],q.back(),nw)) q.pop_back();
            q.push_back(nw);
        }
        F(i,0,n+1) {
            dp2[i] = dp[i];
            dp[i] = -inf;
        }
    }

    int ans = 0;
    F(i, 1, n+1) ans = max(ans, dp2[i]);

    F(i, 1, n+1) {
        if(dp2[i] == ans) {
            int cur = i;
            vi res;
            for(int j = k; j >= 1; j--) {
                res.pb(cur);
                cur = origin[cur][j];
            }
            reverse(res.begin(), res.end());
            cout << ans << endl;
            for(int e : res) cout << e << " ";
            cout << endl;
            return;
        }
    }
}
 
int32_t main() {
    cin.tie(0); ios_base::sync_with_stdio(0);
    #ifdef Local
        freopen("local.in", "r", stdin);
        freopen("local.out", "w", stdout);
    #endif
    int t = 1;
    //cin >> t;
    while(t--) solve();
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...