题解:P15252 [NOSOI R1] Square Sequence
Collapsarr · · 题解
考虑颜色段本身没有区别,并且如果知道每一个颜色段的起始点,就可以复原出全部颜色段。
考虑如何计算答案?可以发现颜色段内部贡献和原序列一致,于是考虑将原序列分割成不同颜色段的贡献差。
考虑令
内部的
#include<bits/stdc++.h>
#include<bits/extc++.h>
using namespace std;
#define int long long
#define double long double
#define ull unsigned int
#define intt __int128
#define pbds __gnu_pbds
#define endl '\n'
inline int read()
{
int x = 0,f = 1;
char ch = getchar();
while('0'>ch||ch>'9')
{
if(ch=='-')
{
f = -1;
}
ch = getchar();
}
while('0'<=ch&&ch<='9')
{
x = (x<<3) + (x<<1) + (ch ^ 48);
ch = getchar();
}
return x * f;
}
const int inf = 1e18,N = 1e6 + 10;
struct tree
{
struct node
{
pair<int,int> line;
node(){line = {0,inf};}
}t[N<<2];
#define ls(i) i<<1
#define rs(i) i<<1|1
inline int fetch(int x,pair<int,int> line)
{
return x * line.first + line.second;
}
inline void update(int i,int l,int r,pair<int,int> line)
{
int mid = (l+r)>>1;
bool L = fetch(l,line) < fetch(l,t[i].line),MID = fetch(mid,line) < fetch(mid,t[i].line);
if(MID)
{
swap(line,t[i].line);
}
if(l==r)
{
return ;
}
if(L^MID)
{
update(ls(i),l,mid,line);
}
else
{
update(rs(i),mid+1,r,line);
}
}
inline int query(int i,int l,int r,int it)
{
if(l==r)
{
return fetch(it,t[i].line);
}
int mid = (l+r)>>1;
return min(fetch(it,t[i].line),(it<=mid)?(query(ls(i),l,mid,it)):(query(rs(i),mid+1,r,it)));
}
}t;
int n,a[N],f[N],s[N],ans;
signed main()
{
cerr<<fixed<<setprecision(6);
auto START = chrono::high_resolution_clock::now();
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
n = read();
for(int i = 1;i<=n;i++)
{
a[i] = read();
s[i] = s[i-1] + (i>1) * (a[i] - a[i-1]) * (a[i] - a[i-1]);
}
for(int i = 2;i<=n;i++)
{
ans = min(ans,f[i]=min(-(a[i]-a[i-1])*(a[i]-a[i-1]),t.query(1,1,N,a[i])+a[i]*a[i]-(a[i]-a[i-1])*(a[i]-a[i-1])));
t.update(1,1,N,{-2*a[i-1],f[i]+a[i-1]*a[i-1]});
}
cout<<s[n]+ans<<endl;
auto END = chrono::high_resolution_clock::now();
chrono::duration<double> ELAPSED = END - START;
cerr<<"Use Time: "<<ELAPSED.count()<<" seconds."<<endl;
return 0;
}