CodeForces-1324 E. Sleeping Schedule dynamic planning + circular array

CodeForces - 1324 E. Sleeping Schedule

Original title address:

http://codeforces.com/contest/1324/problem/E

Basic questions:

Give the number of hours in a day, a good time period [l, r], and n sleep durations stored in the array a, for each sleep duration you can choose to sleep a [i] hours or a [i]-1 hour, If you wake up within [l, r], you think it is good to wake up this time. Ask how many times you can wake up.

The basic idea:

Simple dp, the specific transfer equation is as follows:

 // dp[i][j] 表示第 i 次睡醒时的时间 为 j;
int temp1 = (j - a[i] + h) % h; // 如果这次睡了 a[i] 小时上次的醒来时间是什么时候;
dp[i][j] = max(dp[i][j], dp[i - 1][temp1]);
int temp2 = (j - a[i] + 1 + h) % h;// 如果这次睡了 a[i] - 1 小时上次的醒来时间是什么时候;
dp[i][j] = max(dp[i][j], dp[i - 1][temp2]);
if (j >= l && j <= r) dp[i][j]++; // 如果醒来时间在范围内那么答案加一;

Pay attention to the subtraction operation in the circular array, and then finally take the largest of all possible time answers in the nth wake up.

Reference Code:

#pragma GCC optimize(2)
#pragma GCC optimize(3)
#include <bits/stdc++.h>
using namespace std;
#define IO std::ios::sync_with_stdio(false)
#define int long long
#define rep(i, l, r) for (int i = l; i <= r; i++)
#define per(i, l, r) for (int i = l; i >= r; i--)
#define mset(s, _) memset(s, _, sizeof(s))
#define pb push_back
#define pii pair <int, int>
#define mp(a, b) make_pair(a, b)
#define INF 0x3f3f3f3f
inline int read() {
    int x = 0, neg = 1; char op = getchar();
    while (!isdigit(op)) { if (op == '-') neg = -1; op = getchar(); }
    while (isdigit(op)) { x = 10 * x + op - '0'; op = getchar(); }
    return neg * x;
}
inline void print(int x) {
    if (x < 0) { putchar('-'); x = -x; }
    if (x >= 10) print(x / 10);
    putchar(x % 10 + '0');
}
const int maxn = 2010;
int n,h,l,r;
int a[maxn],dp[maxn][maxn];
signed main() {
    IO;
    cin >> n >> h >> l >> r;
    rep(i, 1, n) cin >> a[i];
    mset(dp, -INF);
    dp[0][0] = 0;
    for (int i = 1; i <= n; i++) {
        for (int j = 0; j < h; j++) {
            // dp[i][j] 表示第 i 次睡醒时的时间 为 j;
            int temp1 = (j - a[i] + h) % h; // 如果这次睡了 a[i] 小时上次的醒来时间是什么时候;
            dp[i][j] = max(dp[i][j], dp[i - 1][temp1]);
            int temp2 = (j - a[i] + 1 + h) % h;// 如果这次睡了 a[i] - 1 小时上次的醒来时间是什么时候;
            dp[i][j] = max(dp[i][j], dp[i - 1][temp2]);
            if (j >= l && j <= r) dp[i][j]++; // 如果醒来时间在范围内那么答案加一;
        }
    }
    int mx = 0;
    for (int i = 0; i < h; i++) mx = max(dp[n][i], mx);
    cout << mx  << endl;
    return 0;
}
Published 23 original articles · praised 7 · visits 1741

Guess you like

Origin blog.csdn.net/weixin_44164153/article/details/104911810