#include <bits/stdc++.h>
using namespace std;
#define ll long long
const ll dx[4] = {-1,0,1,0}, dy[4] = {0,1,0,-1};
const ll N = 1e6;
const ll INF = 1e18;
ll a[N];
ll h[N] , w[N] , dp[N] , pre[N];
struct line{
ll a , b = INF;
ll operator()(ll x)
{
return a * x + b;
}
}st[4 * N];
void up(ll id , ll l , ll r , line cur)
{
ll mid = (l + r) / 2;
bool L = cur(l) < st[id](l);
bool R = cur(mid) < st[id](mid);
if(l + 1== r) return;
if(R) swap(cur , st[id]);
if(L != R)
{
up(id * 2 , l , mid , cur);
}
else up(id * 2 + 1 , mid , r ,cur);
}
ll get(ll id , ll l, ll r , ll x)
{
if(l + 1 == r) return st[id](x);
ll mid = (l + r) / 2;
if(x < mid) return min(st[id](x) , get(id * 2 , l ,mid , x));
else return min(st[id](x) , get(id * 2 + 1 , mid , r , x));
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
ll n;
cin >> n;
for(int i = 1; i <= n ; i++)
{
cin >> h[i];
dp[i] = 1e18;
}
for(int i = 1; i <= n ; i++)
{
cin >> w[i];
pre[i] = pre[i-1] + w[i];
}
/*
dp[i] = dp[j] + (hi - hj)^2 + pre[i] - pre[j-1]
=> đưa về dạng y = a*x + b;
dp[j] + h[i] * h[i] - 2*h[i] *h[j] + h[i] * h[i] + pre[i-1] - pre[j-1];
ta thấy với vị trí hiện tại mà i thì dp[i] = [MIN(-2 * h[j] * h[i] + h[j] * h[j] - pre[j-1] + dp[j])] + h[i] * h[i] + pre[i];
với vai trò là j thì up(a = -2 * h[j] * h[j] , b = dp[i] + h[j] * h[j] - pre[i];
*/
dp[1] = 0;
up(1 , 0 , N , {-2 * h[1] , dp[1] + h[1] * h[1] - pre[1]});
for(int i = 1 ; i <= n ; i++)
{
dp[i] = get(1 , 0 , N , h[i]) + h[i] * h[i] + pre[i-1];
up(1 , 0 , N ,{ -2 * h[i] , dp[i] + h[i] * h[i] - pre[i]});
}
cout<<dp[n]<<'\n';
return 0;
}
/*
6
3 8 7 1 6 6
0 -1 9 1 2 0
*/
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |