P1868 饥饿的奶牛[dp]

P1868 饥饿的奶牛

一句话题意:给\(n\)个区间,区间可以任意选但不能有重复部分,求能选到的最大的点数。

做法:

显然要弄一个\(dp[i]\)表示\([0,i]\)能吃到多少草。

先把所有的区间双关键字从小到大排序。

然后遍历所有的点,找到相对应的区间,更新那个一维的dp。

dp方程看过了之后是显然的。

最后的答案是所有的\(dp[i]\)取最大值。

代码:

/*************************************************************************
 @Author: Garen
 @Created Time : Tue 29 Jan 2019 09:28:06 PM CST
 @File Name: P1868.cpp
 @Description:
 ************************************************************************/
#include<bits/stdc++.h>
using std::cin;
using std::cout;
using std::endl;
#define ll long long
const int maxn = 150005;
const int maxm = 3000005;
struct Nodes {
    int x, y;
} s[maxn];
int dp[maxm];
int n, maxv, ans;

bool cmp(Nodes a, Nodes b) {
    if(a.x == b.x) return a.y < b.y;
    return a.x < b.x;
}
int main() {
    cin >> n;
    for(int i = 1; i <= n; i++) {
        cin >> s[i].x >> s[i].y;
        maxv = std::max(maxv, s[i].y);
    }
    std::sort(s + 1, s + n + 1, cmp);
    int j = 1;
    for(int i = 0; i <= maxv; i++) {
        if(i) dp[i] = std::max(dp[i], dp[i - 1]);
        while(i == s[j].x && j <= n) {
            dp[s[j].y] = std::max(dp[s[j].y], dp[s[j].x - 1] + s[j].y - s[j].x + 1);
            j++;
        }
        ans = std::max(ans, dp[i]);
    }
    cout << ans << endl;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/Garen-Wang/p/10336455.html