洛谷P1941 飞扬的小鸟(背包 dp)

时间:2022-01-31 18:43:21

题意

题目链接

Sol

很显然的dp,设\(f[i][j]\)表示第\(i\)个位置,高度为\(j\)的最小步数

向上转移的时候是完全背包

向下转移判断一下就可以

#include<bits/stdc++.h>
#define Fin(x) {freopen(x, "r", stdin);}
#define chmin(a, b) (a = (a < b ? a : b))
//#define int long long 
using namespace std;
const int MAXN = 10001, mod = 19997, INF = 1e9 + 10;
inline int read() {
    char c = getchar(); int x = 0, f = 1;
    while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
    while(c >= '0' && c <= '9') x = (x * 10 + c - '0') % mod, c = getchar();
    return x * f;
}
int N, M, K;
int x[MAXN], y[MAXN], L[MAXN], H[MAXN], f[2][1001], mx, vis[MAXN];//i:pos  j:height
signed main() {
    N = read(); M = read(); K = read();
    L[0] = 1; H[0] = M;
    for(int i = 1; i <= N; i++) x[i - 1] = read(), y[i - 1] = read(), L[i] = 1, H[i] = M;
    for(int i = 1; i <= K; i++) {
        int p = read(); L[p] = read() + 1; H[p] = read() - 1;
        vis[p] = 1;
    }
    for(int i = 0; i <= M; i++) f[0][i] = 0; int o = 0;
    for(int i = 0, cnt = 0; i < N; i++, o ^= 1) {
        memset(f[o ^ 1], 0x3f, sizeof(f[o ^ 1]));
        if(vis[i]) cnt++;
        for(int j = 0; j <= M; j++) {
            
            int nxt = j + x[i] > M ? M : j + x[i];
            chmin(f[o ^ 1][nxt], f[o][j] + 1);
            chmin(f[o ^ 1][nxt], f[o ^ 1][j] + 1);
            
            if(j - y[i] >= L[i + 1]) chmin(f[o ^ 1][j - y[i]], f[o][j]);
        
        }
        for(int j = 0; j < L[i + 1]; j++) f[o ^ 1][j] = INF;
        for(int j = H[i + 1] + 1; j <= M; j++) f[o ^ 1][j] = INF;
        for(int j = 0; j <= M; j++) 
            if(f[o][j] < INF && vis[i]) 
                mx = cnt;
    } 
    int ans = INF;
    for(int i = L[N]; i <= H[N]; i++) 
        ans = min(ans, f[o][i]);
    if(ans < INF) printf("1\n%d", ans);
    else printf("0\n%d", mx);
    return 0;
}