1. 程式人生 > >[APIO2010]特別行動隊 --- 斜率優化DP

[APIO2010]特別行動隊 --- 斜率優化DP

col 技術分享 efi clu 隊列 ID clas lin n)

[APIO2010]特別行動隊

題面很直白,就不放了。

太套路了,做起來沒點感覺了。

\(dp(i)=dp(j)+a*(s(i)-s(j))^{2}+b*(s(i)-s(j))+c\)

直接推出一個斜率優化的式子上單調隊列就好了

時間/空間復雜度:\(O(n)\)

技術分享圖片
#include<cstdio>
#define sid 1000500
#define ri register int
#define ll long long
#define dd double
using namespace std;

#define getchar() *S ++
char RR[30000005], *S = RR;
inline 
int read(){ int p = 0, w = 1; char c = getchar(); while(c > 9 || c < 0) { if(c == -) w = -1; c = getchar(); } while(c >= 0 && c <= 9) { p = p * 10 + c - 0; c = getchar(); } return p * w; } ll dp[sid], sum[sid];
int q[sid], n, a, b, c; #define x(g) (sum[(g)]) #define y(g) (dp[(g)] + a * sum[(g)] * sum[(g)] - b * sum[(g)]) inline dd s(int i,int j){ return (dd)(y(i) - y(j)) / (dd)(x(i) - x(j)); } int main(){ fread(RR, 1, sizeof(RR), stdin); n = read(); a = read(); b = read(); c = read();
for(ri i = 1; i <= n; i ++) sum[i] = sum[i - 1] + read(); ri fr = 1, to = 1; for(ri i = 1; i <= n; i ++){ while(fr + 1 <= to && s(q[fr],q[fr + 1]) > 2 * a * sum[i]) fr ++; int p = q[fr]; ll pp = sum[i] - sum[p]; dp[i] = dp[p] + a * pp * pp + b * pp + c; while(fr + 1 <= to && s(q[to], q[to - 1]) <= s(i, q[to - 1])) to --; q[++ to]=i; } printf("%lld\n", dp[n]); return 0; }
特別行動隊

[APIO2010]特別行動隊 --- 斜率優化DP