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

点击打开链接

思路:

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

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

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

代码一:

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 typedef long long ll;
 4 #define mem(a) memset(a,0,sizeof(a))
 5 #define mp(x,y) make_pair(x,y)
 6 const int INF = 0x3f3f3f3f;
 7 const ll INFLL = 0x3f3f3f3f3f3f3f3fLL;
 8 inline ll read(){
 9     ll x=0,f=1;char ch=getchar();
10     while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
11     while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
12     return x*f;
13 }
14 //////////////////////////////////////////////////////////////////////////
15 const int maxn = 1e6+10;
16 
17 int n;
18 ll A[maxn],f[maxn],q[maxn];
19 
20 double slope(ll j,ll k){
21     return (1.0*(f[j]-f[k]-k*(k+1)/2+j*(j+1)/2))/(j-k);
22 }
23 
24 int main(){
25     n = read();
26     for(int i=1; i<=n; i++)
27         A[i] = read();
28 
29     int L=0,R=0;
30     for(int i=1; i<=n; i++){
31         while(L<R && slope(q[L+1],q[L])<i) L++;
32         ll j = q[L];
33         f[i] = f[j] + (i-j)*(i-j-1)/2 + A[i];
34         while(L<R && slope(i,q[R])<slope(q[R],q[R-1])) R--;
35         q[++R] = i;
36     }
37 
38     cout << f[n] << endl;
39 
40     return 0;
41 }

 


代码二:

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 typedef long long ll;
 4 #define mem(a) memset(a,0,sizeof(a))
 5 #define mp(x,y) make_pair(x,y)
 6 const int INF = 0x3f3f3f3f;
 7 const ll INFLL = 0x3f3f3f3f3f3f3f3fLL;
 8 inline ll read(){
 9     ll x=0,f=1;char ch=getchar();
10     while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
11     while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
12     return x*f;
13 }
14 //////////////////////////////////////////////////////////////////////////
15 const int maxn = 1e6+10;
16 
17 struct node{
18     ll x,y;
19 }now,q[maxn];
20 
21 int n;
22 ll A[maxn];
23 
24 ll cross(node a,node b,node c){
25     return (b.x-a.x)*(c.y-a.y)-(c.x-a.x)*(b.y-a.y);
26 }
27 
28 int main(){
29     n = read();
30     for(int i=1; i<=n; i++)
31         A[i] = read();
32 
33     int L=0,R=0;
34     for(int i=1; i<=n; i++){
35         while(L<R && q[L+1].y-i*q[L+1].x <= q[L].y-i*q[L].x) L++;
36         now.x = i;
37         now.y = q[L].y-(ll)i*q[L].x+(ll)i*i+A[i];
38         while(L<R && cross(q[R-1],q[R],now)<=0) R--;
39         q[++R] = now;
40     }
41 
42     cout << q[R].y-(ll)n*(n+1)/2 << endl;
43 
44     return 0;
45 }

 

posted @ 2017-02-23 13:44  _yxg123  阅读(100)  评论(0编辑  收藏  举报