首页 > 代码库 > 斜率优化回顾

斜率优化回顾

(懒得排版了....^w^)
今天刷了一天Dp的题,做恶心了,刚刚做到一个既能斜率优化,又能四边形不等式优化的题 :    hdu 3480 Division
                 斜率优化....好吧,我忘了怎么写了........
                  YY.....
                  .....
                .....
                .....
bingo....  
                           在单调队列进行的斜率优化时,用单调队列维护解“优”的单调性,即,越优的越在前面。。。
                          简要总结一下(以f[i] = min{ f[j] + (a[i] - a[j])^2 } i < j ,a[i]单调递增 为例 ):
                   一、对于决策i,找较优
                       f[j1] - (a[i] - a[j1])^2 <= f[j2] - (a[i] - a[j2])^2
                              整理:
                          设F[i] = f[i] + a[i]^2
                       F[j1] - F[j2] <= 2a[i] (a[j1] - a[j2])
                  代码:
                while(front + 1 < rear)
                    if(F[q[front + 1]] - F[q[front]] <= 2a[i] (a[q[front + 1]] - a[q[front]]))           
                           front ++;        //                       q[front]     不如 q[front + 1]优
                    else    break;                                 //        找到当前最优
                  二、取出
                   int k = q[front];
                    dp[i] = dp[k] + (a[i] - a[k]) ^ 2;
                 三、把 i 放入队列,维护凸性质(维护斜率的单调性)
                        设 q1 = q[rear - 1],q2 = q[rear - 2]                         
                        while(front + 1 < rear)
                            if( (F[i] - F[q1]) * (a[q2] - a[q1]) <= (F[q2] - F[q1]) * (a[i] - a[q1]) )    // 因为q2 < q1 < i & a[i]单调递增   
                                rear --;            // q1不如 i 优
                            else break;         // q1比i优
                         q[rear ++] = i;