codeforces-4D Mysterious Present(二维递增子序列)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/GrimCake/article/details/79956465

链接:http://codeforces.com/problemset/problem/4/D

题意:二维递增子序列

题解:先排序,dp【i】表示以i结尾的最长递增子序列的长度,dp【i】= max{dp【j】+1,dp【i】}  j<i, p[i].w>p[j].w&& p[i].h>p[j].h, 注意边界及一些特殊情况

代码:
#include<iostream>
#include<cstring>
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;

struct node{
    int w, h;
    int id;
}p[5010];

int n;
int w0, h0;
int dp[5010];
int Next[5010];

bool cmp(node a, node b){
    if(a.w == b.w) return a.h<b.h;
    return a.w<b.w;
}

void output(int x){
    if(Next[x] == -1){
        printf("%d", x);
        return;
    }
    output(Next[x]);
    printf(" %d", x);
}
int main(){
    scanf("%d%d%d", &n, &w0, &h0);
    for(int i = 1; i<=n; i++){
        scanf("%d%d", &p[i].w, &p[i].h);
        p[i].id = i;
    }
    sort(p+1, p+1+n, cmp);
    if(p[1].w>w0 && p[1].h>h0) dp[1] = 1;
    memset(Next, -1, sizeof(Next));
    for(int i = 1; i<=n; i++){
        bool flag = true;
        for(int j = 1; j<i; j++){
            //cout<<i<<" "<<j<<" "<<p[i].w<<" "<<p[i].h<<" "<<p[j].w<<" "<<p[j].h<<endl;
            if(p[j].w<p[i].w && p[j].h<p[i].h && p[i].w>w0 && p[i].h>h0){
                //dp[i] = max(dp[i], dp[j]+1);
                //cout<<i<<" "<<dp[i]<<endl;
                if(dp[j]+1>dp[i] && p[j].w>w0 && p[j].h>h0){
                    dp[i] = dp[j]+1;
                    Next[p[i].id] = p[j].id;
                    flag = false;
                }
                //cout<<i<<" "<<dp[i]<<endl;
            }
        }
        if(flag && p[i].w>w0 && p[i].h>h0){
            dp[i] = 1;
        }
    }
    int res = -1;
    int temp;
    for(int i = 1; i<=n; i++){
        //res = max(res, dp[i]);
        if(dp[i]>res){
            res = dp[i];
            temp = p[i].id;
        }
    }
    printf("%d\n", res);
    if(res==0) return 0;
    /*cout<<temp<<endl;
    for(int i = 1; i<=n; i++){
        cout<<Next[i]<<" ";
    }
    cout<<endl;*/
    output(temp);
    printf("\n");



    return 0;
}

/*
5 10 10
22 23
17 19
13 17
8 12
2 6
*/

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页