Submission #155536

#TimeUsernameProblemLanguageResultExecution timeMemory
155536Learner99K blocks (IZhO14_blocks)C++14
100 / 100
659 ms159740 KiB
#include <bits/stdc++.h>

using namespace std;

#define int long long
#define N 100006
int inf =10000000000006;

int dp[N][101];
int ind[N][101];
int pre[N];

int32_t main()
{
    int n, k;
    cin>>n>>k;

    vector < int > a(n+1);
    for(int i=1;i<=n;i++)
        cin>>a[i];

    a[0] = inf;

    
    

    int cur = 1;
    for(int i=1;i<=n;i++)
    {
        if( a[cur] < a[i])
                cur = i;
        dp[i][1] = a[cur];
        ind[i][1] = cur;
    }

    for(int j=2;j<=k;j++)
    {
        stack < int > s;
        for(int i=j;i<=n;i++)
        {
            dp[i][j] = dp[i-1][j-1] + a[i];
            ind[i][j] = i;

            while(s.size())
            {
                int temp = s.top();
                if( a[temp] < a[i] )
                {
                if(dp[temp][j] - a[ind[temp][j]] + max(a[ind[temp][j]], a[i]) < dp[i][j])
                {
                dp[i][j] = dp[temp][j] - a[ind[temp][j]] + max(a[ind[temp][j]], a[i]);
                if(a[i] < a[ind[temp][j]])
                    ind[i][j] = ind[temp][j];
                }
                    s.pop();
                }
                else
                {
                    break;
                }
            }


            if(s.size())
            {
                int cur = s.top();
                if( dp[i][j] > dp[cur][j])
                {
                    dp[i][j] = dp[cur][j];
                    ind[i][j] = ind[cur][j];
                }
            }
            s.push(i);
        }
    }

    cout<<dp[n][k]<<endl;
    return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...