DP单调队列--斜率优化P3195

题意:https://www.luogu.com.cn/problem/P3195

思路:https://www.luogu.com.cn/problemnew/solution/P3195

 #define IOS ios_base::sync_with_stdio(0); cin.tie(0);
#include <cstdio>//sprintf islower isupper
#include <cstdlib>//malloc exit strcat itoa system("cls")
#include <iostream>//pair
#include <fstream>//freopen("C:\\Users\\13606\\Desktop\\Input.txt","r",stdin);
#include <bitset>
//#include <map>
//#include<unordered_map>
#include <vector>
#include <stack>
#include <set>
#include <string.h>//strstr substr strcat
#include <string>
#include <time.h>// srand(((unsigned)time(NULL))); Seed n=rand()%10 - 0~9;
#include <cmath>
#include <deque>
#include <queue>//priority_queue<int, vector<int>, greater<int> > q;//less
#include <vector>//emplace_back
//#include <math.h>
#include <cassert>
#include <iomanip>
//#include <windows.h>//reverse(a,a+len);// ~ ! ~ ! floor
#include <algorithm>//sort + unique : sz=unique(b+1,b+n+1)-(b+1);+nth_element(first, nth, last, compare)
using namespace std;//next_permutation(a+1,a+1+n);//prev_permutation
//******************
clock_t __START,__END;
double __TOTALTIME;
void _MS(){__START=clock();}
void _ME(){__END=clock();__TOTALTIME=(double)(__END-__START)/CLOCKS_PER_SEC;cout<<"Time: "<<__TOTALTIME<<" s"<<endl;}
//***********************
#define rint register int
#define fo(a,b,c) for(rint a=b;a<=c;++a)
#define fr(a,b,c) for(rint a=b;a>=c;--a)
#define mem(a,b) memset(a,b,sizeof(a))
#define pr printf
#define sc scanf
#define ls rt<<1
#define rs rt<<1|1
typedef pair<int,int> PII;
typedef vector<int> VI;
typedef unsigned long long ull;
typedef long long ll;
typedef double db;
const double E=2.718281828;
const double PI=acos(-1.0);
const ll INF=(1LL<<);
const int inf=(<<);
const double ESP=1e-;
const int mod=(int)1e9+;
const int N=(int)1e6+; int n,L;
int a[N];
db dp[N],sum[N];
db A(int x)
{
return sum[x]+x;
}
db B(int x)
{
return sum[x]+x+L+;
}
db X(int x)
{
return B(x);
}
db Y(int x)
{
return dp[x]+B(x)*B(x);
}
double slope(int a,int b)
{
return 1.0*(Y(a)-Y(b))/(1.0*(X(a)-X(b)));
} class mydeque{
public:
int len=;
int p[N];
int l,r,tot;
void init()
{
l=;r=;
tot=;
}
int size()
{
return tot;
}
int pos(int x)
{
return (x+len)%len;
}
int f()
{
return p[l];
}
int b()
{
return p[r];
}
void pf(int x)
{
tot++;
l=pos(l-);
p[l]=x;
}
void pb(int x)
{
tot++;
r=pos(r+);
p[r]=x;
}
void popf()
{
p[l]=;
l=pos(l+);
tot--;
}
void popb()
{
p[r]=;
r=pos(r-);
tot--;
}
}q; int main()
{
q.init();//初始化有dp[0](l=r=1而不是l=1,r=0,tot=0),因为要用到
sc("%d%d",&n,&L);
for(int i=;i<=n;++i)sc("%d",&a[i]),sum[i]=a[i]+sum[i-];
for(int i=;i<=n;++i)
{
while(q.l<q.r&&slope(q.f(),q.p[q.pos(q.l+)])<2.0*A(i))q.popf();
dp[i]=dp[q.f()]+(A(i)-B(q.f()))*(A(i)-B(q.f()));
while(q.l<q.r&&slope(q.p[q.pos(q.r-)],q.b())>slope(q.p[q.pos(q.r-)],i))q.popb();
q.pb(i);
}
pr("%lld\n",(ll)dp[n]);
return ;
} /**************************************************************************************/
上一篇:复数 一级ADT实现


下一篇:土地购买 (斜率优化dp)