欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-03-26 09:34:38
题意 "题目链接" Sol 很显然的dp,设$f[i][j]$表示第$i$个位置,高度为$j$的最小步数 向上转移的时候是完全背包 向下转移判断一下就可以 cpp include define Fin(x) {freopen(x, "r", stdin);} define chmin(a, b) ( ......

题意

题目链接

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;
}