Question:HDU 3507
听说这是idy002的第一道斜率优化题
方程和优化一分钟推出来,4分钟写好程序,样例过了,好,交!
但为什么我会在这道题上TLE和WA……
这道题会卡死你的……
因为可能会出现cost[i]=0的情况,那么在出队尾的时候需要注意当两两cost相等时,也就是对于cost为0导致两点sum(前缀和),dp都是相等的情况,一定不能判断q[ t-1 ] & q[ t ]的斜率是否 大于 q[ t ] & i 的斜率,而是 大于等于!
然后就A了!长见识了……
代码:
#include<bits/stdc++.h>
const int N=500000+5;
using namespace std;
long long sum[N],dp[N];
int cost[N],n,m,h,t,q[N<<2];
inline void read(int &x) {
int f=1;x=0;char c=getchar();
while(c>'9'||c<'0') {if(c=='-') f=-1;c=getchar();}
while(c>='0'&&c<='9') x=10*x+c-48,c=getchar();
x=x*f;
}
bool slope_1(int j,int k,int i){
return 2*sum[i]*(sum[k]-sum[j])>=dp[k]-dp[j]+sum[k]*sum[k]-sum[j]*sum[j];
}
bool slope_2(int j,int k,int x,int y){
return (dp[k]-dp[j]+sum[k]*sum[k]-sum[j]*sum[j])*(sum[y]-sum[x])>=(dp[y]-dp[x]+sum[y]*sum[y]-sum[x]*sum[x])*(sum[k]-sum[j]);
}
int main(){
ios::sync_with_stdio(false);
freopen("test.in","r",stdin);
while(scanf("%d%d",&n,&m)==2){
h=t=0;
memset(dp,0,sizeof(dp));
memset(q,0,sizeof(q));
for(int i=1;i<=n;i++){
read(cost[i]);
sum[i]=sum[i-1]+1ll*cost[i];
}
for(int i=1;i<=n;i++){
while(h<t && slope_1(q[h],q[h+1],i)) h++;
int tmp=q[h];
dp[i]=dp[tmp]+(sum[i]-sum[tmp])*(sum[i]-sum[tmp])+1ll*m;
while(h<t && slope_2(q[t-1],q[t],q[t],i)) t--;
q[++t]=i;
}
cout<<dp[n]<<endl;
}
return 0;
}
//hdu 3507