Solution to a problem [war] AcWing1089 transfer

Face questions

DP template monotonous queue optimization problem.

We consider setting \ (dp_ {i} \) represents the \ (1 \) to \ (I \) can be accurately transmitted information, and the first \ (I \) th beacon signal sent minimum cost.

Difficult to draw transfer equation: \ (dp_ {I} = \ {min_ IM \ Leq J \ I-Leq. 1} \ {dp_j \} a_i + \) ( \ (a_i \) for the first \ (I \) th beacon Taiwan issued a cost signal).

See conditions for transfer: \ (IM \ Leq J \ Leq i - 1 \) , which is actually a sliding window problem.

With a maintenance queue length is monotonic \ (m \) of the sliding window.

The last answer is \ (\ {nm-min_. 1 \ Leq I \ n-Leq} \ {dp_i \} \) .

#include <bits/stdc++.h>

using namespace std;

const int N = 200003;

int n, m, a[N], q[N], hh, tt, ans, dp[N];

int main()
{
    cin >> n >> m;
    for (int i = 1; i <= n; i+=1) cin >> a[i];
    hh = 0, tt = 0; //注意一开始队列中是有元素的
    for (int i = 1; i <= n; i+=1) //对于每一个烽火台进行转移
    {
        while (hh <= tt && q[hh] < i - m) ++hh; //队头是否在区间内
        dp[i] = dp[q[hh]] + a[i]; //DP 值转移
        while (hh <= tt && dp[q[tt]] >= dp[i]) --tt; //维护队列单调性
        q[++tt] = i; //加入队列
    }
    ans = 2000000007; //答案
    for (int i = n - m + 1; i <= n; i+=1) 
        ans = min(ans, dp[i]); //答案要从 n - m + 1 ~ n 的 DP 值中取最小值
    cout << ans << endl;
    return 0;
}

Guess you like

Origin www.cnblogs.com/xsl19/p/12362080.html