题解 亿个社区
考虑暴力是 \(O(n^2k)\) 的
考虑暴力这份码:
for (int i=1; i<=n; ++i)
for (int j=1; j<=k; ++j)
for (int l=0; l<i; ++l)
f[i][j]=min(f[i][j], f[l][j-1]+sqr(t[i]-t[l+1]));
发现最后这个转移可以把括号拆开,然后动态凸包优化
复杂度 \(O(nk\log n)\)
点击查看代码
#include <bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f3f3f3f3f3f
#define N 100010
#define fir first
#define sec second
#define ll long long
//#define int long long
char buf[1<<21], *p1=buf, *p2=buf;
#define getchar() (p1==p2&&(p2=(p1=buf)+fread(buf, 1, 1<<21, stdin)), p1==p2?EOF:*p1++)
inline int read() {
int ans=0, f=1; char c=getchar();
while (!isdigit(c)) {if (c=='-') f=-f; c=getchar();}
while (isdigit(c)) {ans=(ans<<3)+(ans<<1)+(c^48); c=getchar();}
return ans*f;
}
int n, k;
ll t[N];
inline ll sqr(ll t) {return t*t;}
namespace force{
ll f[10100][110];
void solve() {
memset(f, 0x3f, sizeof(f));
f[0][0]=0;
for (int i=1; i<=n; ++i)
for (int j=1; j<=k; ++j)
for (int l=0; l<i; ++l)
f[i][j]=min(f[i][j], f[l][j-1]+sqr(t[i]-t[l+1]));
printf("%lld\n", f[n][k]);
}
}
namespace task1{
ll f[10010][110];
struct vec{
mutable ll k, b; mutable double p;
vec(ll x, ll y):k(x),b(y),p(0){}
};
inline bool operator < (vec a, vec b) {return a.k>b.k;}
inline bool operator < (vec a, double b) {return a.p<b;}
struct convex:multiset<vec, less<>>{
const double inf=1e30;
inline double qmeet(vec a, vec b) {return double(b.b-a.b)/double(a.k-b.k);}
bool isect(iterator a, iterator b) {
if (b==end()) return a->p=inf, 0;
if (a->k==b->k) a->p = a->b > b->b ? -inf : inf;
else a->p = qmeet(*a, *b);
return a->p >= b->p;
}
void ins(vec t) {
auto z=insert(t), y=z++, x=y;
while (isect(y, z)) z=erase(z);
if (x!=begin() && isect(--x, y)) isect(x, y=erase(y));
while ((y=x)!=begin() && (--x)->p >= y->p) isect(x, y=erase(y));
}
ll qmin(ll x) {
if (empty()) return INF;
auto it=lower_bound(x);
return it->k*x+it->b;
}
}con[110], tem;
// set<pair<ll, ll>> s[110];
void solve() {
con[0].ins({-2*t[1], sqr(t[1])});
// s[0].insert({-2*t[1], sqr(t[1])});
for (int i=1; i<=n; ++i) {
for (int j=1; j<=min(i, k); ++j) f[i][j]=sqr(t[i])+con[j-1].qmin(t[i]); //, cout<<con[j-1].qmin(t[i])<<endl;
for (int j=1; j<=min(i, k); ++j) con[j].ins({-2*t[i+1], sqr(t[i+1])+f[i][j]});
// for (int j=1; j<=min(i, k); ++j) {
// f[i][j]=INF;
// for (auto it:s[j-1]) f[i][j]=min(f[i][j], sqr(t[i])+t[i]*it.fir+it.sec);
// }
// for (int j=1; j<=min(i, k); ++j) s[j].insert({-2*t[i+1], sqr(t[i+1])+f[i][j]});
}
printf("%lld\n", f[n][k]);
}
}
signed main()
{
freopen("community.in", "r", stdin);
freopen("community.out", "w", stdout);
n=read(); k=read();
for (int i=1; i<=n; ++i) t[i]=read();
// force::solve();
task1::solve();
return 0;
}