您的位置:首页 > 其它

bzoj 3156 防御准备(斜率优化+DP)

2017-02-23 13:44 375 查看
点击打开链接

思路:

f[i] 表示前i个的最小花费 

转移:f[i] = f[j] + (i-j)*(i-j-1)/2 + A[i];

需要注意的是过程中数据超范围

代码一:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define mem(a) memset(a,0,sizeof(a))
#define mp(x,y) make_pair(x,y)
const int INF = 0x3f3f3f3f;
const ll INFLL = 0x3f3f3f3f3f3f3f3fLL;
inline ll read(){
ll x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
//////////////////////////////////////////////////////////////////////////
const int maxn = 1e6+10;

int n;
ll A[maxn],f[maxn],q[maxn];

double slope(ll j,ll k){
return (1.0*(f[j]-f[k]-k*(k+1)/2+j*(j+1)/2))/(j-k);
}

int main(){
n = read();
for(int i=1; i<=n; i++)
A[i] = read();

int L=0,R=0;
for(int i=1; i<=n; i++){
while(L<R && slope(q[L+1],q[L])<i) L++;
ll j = q[L];
f[i] = f[j] + (i-j)*(i-j-1)/2 + A[i];
while(L<R && slope(i,q[R])<slope(q[R],q[R-1])) R--;
q[++R] = i;
}

cout << f
<< endl;

return 0;
}

代码二:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define mem(a) memset(a,0,sizeof(a))
#define mp(x,y) make_pair(x,y)
const int INF = 0x3f3f3f3f;
const ll INFLL = 0x3f3f3f3f3f3f3f3fLL;
inline ll read(){
ll x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
//////////////////////////////////////////////////////////////////////////
const int maxn = 1e6+10;

struct node{
ll x,y;
}now,q[maxn];

int n;
ll A[maxn];

ll cross(node a,node b,node c){
return (b.x-a.x)*(c.y-a.y)-(c.x-a.x)*(b.y-a.y);
}

int main(){
n = read();
for(int i=1; i<=n; i++)
A[i] = read();

int L=0,R=0;
for(int i=1; i<=n; i++){
while(L<R && q[L+1].y-i*q[L+1].x <= q[L].y-i*q[L].x) L++;
now.x = i;
now.y = q[L].y-(ll)i*q[L].x+(ll)i*i+A[i];
while(L<R && cross(q[R-1],q[R],now)<=0) R--;
q[++R] = now;
}

cout << q[R].y-(ll)n*(n+1)/2 << endl;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  动态规划