题解:P7823 「RdOI R3」闹钟
首先每个任务可以钦定一个变量完成。
设
后面的意思是,该变量从
你注意到设
即可做到
然后主要考虑
如果没有这个绝对值就做完了。然后你发现我们分讨
具体实现就是,将
线段树单点赋值区间求
代码使用超快科技,据说比 lxl 标算快。
#include<bits/stdc++.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
using namespace std;
typedef pair<int,int> PII;
typedef long long ll;
const int N=1000005;
char*pc;
int n,m,a[N],b[N];
static ll t1[N],t2[N];
struct node{
int x,i;
bool operator<(const node&rhs)const{
return x<rhs.x;
}
}lsh[N];
int RD(){
int x=0;
char ch=*pc++;
while(ch<48||ch>57)ch=*pc++;
while(ch>=48&&ch<=57){
x=(x<<3)+(x<<1)+(ch^48);
ch=*pc++;
}
return x;
}
void add(int p,ll x,ll y){
ll k1=x+y,k2=x-y;
for(int t=p;t;t-=t&-t)t1[t]=t1[t]>k1?k1:t1[t];
for(;p<=m;p+=p&-p)t2[p]=t2[p]>k2?k2:t2[p];
}
ll query(int p,int ax){
ll r1=1e18,r2=1e18;
for(int t=p;t<=m;t+=t&-t)r1=r1>t1[t]?t1[t]:r1;
for(;p;p-=p&-p)r2=r2>t2[p]?t2[p]:r2;
return min(r2+ax,r1-ax);
}
signed main(){
freopen("express.in","r",stdin);
freopen("express.out","w",stdout);
struct stat state;
fstat(0,&state);
pc=(char*)mmap(NULL,state.st_size,PROT_READ,MAP_PRIVATE,0,0);
n=RD();
for(int i=1;i<=n;i++){
lsh[i].x=a[i]=RD();
lsh[i].i=i;
}
m=n+1,lsh[m]={0,0};
sort(lsh+1,lsh+m+1);
lsh[0].x=1;
for(int i=1;i<=m;i++)
b[ lsh[i].i ]=b[ lsh[i-1].i ]+(lsh[i].x!=lsh[i-1].x);
m=b[ lsh[m].i ];
ll mn=1e18,nm=a[1];
memset(t1,0x3f,sizeof t1);
memset(t2,0x3f,sizeof t2);
add(1,0,0);
for(int i=1;i<n;i++){
int t=(a[i]>a[i+1]?a[i]-a[i+1]:a[i+1]-a[i]);
ll mp=query(b[i+1],a[i+1])-t;
add(b[i],mp,a[i]);
mn=mn>mp?mp:mn;nm+=t;
}
printf("%lld",mn+nm);
}