【单调队列优化】[CF372C] Watching Fireworks is Fun
突然发现我可能单调队列都打不来了...我太菜了...
这道题显然有$$f[i][j]=min\{f[i-1][k]+\vert j-a[i] \vert\}$$
则$ans=\sum_{i=1}^{m} b_i - min_{j=1}^{n}\{f[m][j]\}$
令$len=(t[i]-t[i-1])*d$则其中k满足$$k∈[j-len,j+len]$$
$f[i][]$只与$f[i-1][]$有关,所以可以把第一维压掉
不难弄出一个$O(n^2m)$的代码:
#include<bits/stdc++.h> #define int long long #define writeln(x) write(x),puts("") #define writep(x) write(x),putchar(' ') using namespace std; inline int read(){ int ans=0,f=1;char chr=getchar(); while(!isdigit(chr)){if(chr=='-') f=-1;chr=getchar();} while(isdigit(chr)){ans=(ans<<3)+(ans<<1)+chr-48;chr=getchar();} return ans*f; }void write(int x){ if(x<0) putchar('-'),x=-x; if(x>9) write(x/10); putchar(x%10+'0'); }const int M = 150005; int f[2][M],n,m,d,ans=0x3f3f3f3f,sum; struct P{int a,b,t;}a[M]; signed main(){ n=read(),m=read(),d=read(),sum=0; for(int i=1;i<=m;i++){ int x=read(),y=read(),z=read(); sum+=y; a[i]=(P){x,y,z}; } for(int i(1);i<=n;i++)f[1][i]=abs(a[1].a-i); for(int i(2);i<=m;i++){ memset(f[i&1],0x3f,sizeof(f[i&1])); int len=(a[i].t-a[i-1].t)*d; for(int j=1;j<=n;j++){ for(int k=max(1ll,j-len);k<=min(j+len,n);k++) f[i&1][j]=min(f[i&1][j],f[i&1^1][k]+abs(a[i].a-j)); if(i==m)ans=min(ans,f[i&1][j]); } } cout<<sum-ans<<endl; return 0; }
但是显然会T,注意到上面k的范围,可以考虑单调队列优化,对于每一次的$i,j$,对$[j-len,j]$跑一次滑动窗口,对$[j,j+len]$跑一次滑动窗口取最小值即可
1 #include<bits/stdc++.h> 2 #define int long long 3 #define writeln(x) write(x),puts("") 4 #define writep(x) write(x),putchar(' ') 5 using namespace std; 6 inline int read(){ 7 int ans=0,f=1;char chr=getchar(); 8 while(!isdigit(chr)){if(chr=='-') f=-1;chr=getchar();} 9 while(isdigit(chr)){ans=(ans<<3)+(ans<<1)+chr-48;chr=getchar();} 10 return ans*f; 11 }void write(int x){ 12 if(x<0) putchar('-'),x=-x; 13 if(x>9) write(x/10); 14 putchar(x%10+'0'); 15 }const int M = 150005; 16 int f[2][M],n,m,d,ans=0x3f3f3f3f,sum,q[M]; 17 struct P{int a,b,t;}a[M]; 18 signed main(){ 19 n=read(),m=read(),d=read(),sum=0; 20 for(int i=1;i<=m;i++){ 21 int x=read(),y=read(),z=read(); 22 sum+=y;a[i]=(P){x,y,z}; 23 }for(int i(1);i<=n;i++)f[1][i]=abs(a[1].a-i); 24 for(int i(2);i<=m;i++){ 25 int len=(a[i].t-a[i-1].t)*d,l=1,r=0; 26 for(int j=1;j<=n;j++){ 27 while(l<=r&&q[l]<j-len)++l; 28 while(l<=r&&f[i&1^1][q[r]]>f[i&1^1][j])--r; 29 q[++r]=j; 30 f[i&1][j]=f[i&1^1][q[l]]+abs(j-a[i].a); 31 if(i==m)ans=min(ans,f[i&1][j]); 32 }l=1,r=0; 33 for(int j=n;j>=1;j--){ 34 while(l<=r&&q[l]-len>j)++l; 35 while(l<=r&&f[i&1^1][q[r]]>f[i&1^1][j])--r; 36 q[++r]=j; 37 f[i&1][j]=min(f[i&1][j],f[i&1^1][q[l]]+abs(j-a[i].a)); 38 if(i==m)ans=min(ans,f[i&1][j]); 39 } 40 }cout<<sum-ans<<endl; 41 return 0; 42 }