当前位置: 代码迷 >> 综合 >> CF4D D. Mysterious Present
  详细解决方案

CF4D D. Mysterious Present

热度:26   发布时间:2023-12-02 14:38:58.0

做题链接: D. Mysterious Present
题目:

给出一个限制(w, h),和n个物品的二维信息(wi,hi)求物品二维都满足wi > w, hi > h的前提下的最长二维严格上升子序列以及长度(wi > wi - 1, hi > hi - 1)
如果找不到任何物品就直接输出0.
物品的顺序可以任意,不做要求
1≤n≤5000, 1≤w,h≤1,000,000

解决:

n只有5000,显然本题是具有二维限制的求最长上升子序问题,并输出子序
先按照(x,y)为第一、第二关键字升序排序,然后做一遍最长上升子序,并且注意记录状态转移的路径。

代码:

#include <bits/stdc++.h>
using namespace std;
const int N = 5010;
struct Node{
    int x, y;int id;
};
bool cmp(Node a, Node b)
{
    if (a.x == b.x) return a.y < b.y;return a.x < b.x;
}
int n, xx, yy;
vector<Node> q;
struct {
    int val, pre;
}dp[N];int main()
{
    cin >> n >> xx >> yy;for (int i = 1; i <= n; i ++ ){
    int x, y; scanf("%d%d", &x, &y);if (x <= xx || y <= yy) continue;q.push_back({
    x, y, i});}q.push_back({
    xx, yy, -1});sort(q.begin(), q.end(), cmp);int mx = -1, id = -1;for (int i = 1; i < q.size(); i ++ )for (int j = 0; j < i && q[j].x < q[i].x; j ++ )if (q[j].y < q[i].y){
    if (dp[i].val < dp[j].val + 1){
    dp[i].val = dp[j].val + 1;dp[i].pre = j;if (mx < dp[i].val){
    mx = dp[i].val;id = i;}}}if (q.size() == 1){
    cout << 0 << endl;return 0;}// cout << mx << " " << id << endl;// cout << id << " " << q[id].id <<endl;vector<int> ans;while (id != -1 && id != 0){
    ans.push_back(q[id].id);// printf("now.id = %d, pre.id = %d\n", q[id].id, q[dp[id].pre].id);id = dp[id].pre;}cout << ans.size() << endl;reverse(ans.begin(), ans.end());for (int x : ans) cout << x << " ";cout << endl;return 0;
}
  相关解决方案