Luo Gu P5017 car ferry

topic

A wide variety of practice questions, DP state practices a lot.

I \ (dp [i] \) represents the start time of the i-seconds and then wrote a very good equation dp

\ (dp [i] = dp wait time [j] + i car \) J belonging to the i-2m ~ im.

Then the waiting time i prefix and the car can be used to optimize obtained, although very slow, but enough to pass this question of.

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#define N 6011101
using namespace std;
int n, m, t[N]; //等待时间不是最终时间 
int minn = 2147483647, dp[N], tim[N], per[N];//dp[i]表示第i时间所等待的时间和的最小值。
inline void init()
{
    scanf("%d%d", &n, &m);
    minn = n * m;
    for (int i = 1; i <= n; i++) scanf("%d", &t[i]);
    sort(t + 1, t + 1 + n);
    for (int i = 0, k = 1; i <= t[n] + m; i++)
    {
        tim[i] = tim[i - 1];
        per[i] = per[i - 1];
        while (t[k] == i)
        {
            tim[i] += t[k];
            per[i] ++;
            k++;
        }
    }
}
int main()
{
    init();
    memset(dp, 123, sizeof(dp));
    for (int i = 0; i <= m; i++)//预处理m以内的dp
        dp[i] = per[i] * i - tim[i];
    for (int i = m; i <= t[n] + m - 1; i++)
    {
        for (int j = max(i - m - m, 0); j <= i - m; j++)
            dp[i] = min(dp[i], dp[j] + (per[i] - per[j]) * i - (tim[i] - tim[j]));
    }
    for (int i = t[n]; i <= t[n] + m - 1; i++)
        minn = min(minn, dp[i]);
    printf("%d", minn);
    return 0;
}

Guess you like

Origin www.cnblogs.com/liuwenyao/p/11139624.html