This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include<bits/stdc++.h>
#define ll long long
#define ld long double
#define fi first
#define se second
#define pb push_back
#define all(c) c.begin(), c.end()
#define pii pair<int, int>
#define pll pair<long long, long long>
using namespace std;
const int N = 1e6 + 10;
struct line
{
ll a, b;
line() {};
line(ll a, ll b) : a(a), b(b) {};
};
int n;
ll a[N], dp[N];
bool bad(line A, line B, line C)
{
return (ld) (C.b - A.b) / (A.a - C.a) < (ld) (B.b - A.b) / (A.a - B.a);
}
void addLine(vector<line> &memo, line cur)
{
int k = memo.size();
while(k >= 2 && bad(memo[k - 2], memo[k - 1], cur))
{
memo.pop_back();
k--;
}
memo.pb(cur);
}
ll Fn(line A, ll x)
{
return A.a * x + A.b;
}
ll Query(vector<line> &memo, ll x)
{
int l = 0, r = memo.size() - 1;
if(r == - 1) return 0ll;
while(l < r)
{
int mid = l + r >> 1;
if(Fn(memo[mid], x) < Fn(memo[mid + 1], x)) r = mid;
else l = mid + 1;
}
return Fn(memo[l], x);
}
vector<line> memo;
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
//freopen("DISCHARG.inp", "r", stdin);
//freopen("DISCHARG.out", "w", stdout);
cin >> n;
for(int i = 1; i <= n; i++) cin >> a[i];
reverse(a + 1, a + 1 + n);
vector<int> pos;
for(int i = 1; i <= n; i++)
{
while(!pos.empty() && a[pos.back()] <= a[i]) pos.pop_back();
pos.pb(i);
}
for(int i = 1; i <= pos.size(); i++)
{
addLine(memo, line(a[pos[i - 1]], dp[i - 1]));
dp[i] = Query(memo, pos[i - 1]);
// cout << dp[i] << '\n';
}
cout << dp[pos.size()];
return 0;
}
Compilation message (stderr)
Discharging.cpp: In function 'long long int Query(std::vector<line>&, long long int)':
Discharging.cpp:53:21: warning: suggest parentheses around '+' inside '>>' [-Wparentheses]
53 | int mid = l + r >> 1;
| ~~^~~
Discharging.cpp: In function 'int main()':
Discharging.cpp:78:22: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
78 | for(int i = 1; i <= pos.size(); i++)
| ~~^~~~~~~~~~~~~
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |