UVa 10131 - Is Bigger Smarter?

本文介绍了一种解决最长上升子序列问题的算法实现,通过先排序后求解IQ的最长下降子序列来间接找到答案。提供了完整的C++代码示例,并展示了如何打印出具体的子序列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最长上升子序列,不过需要略微处理一下,先按重量从小到大排一下序,然后找IQ的最长下降子序列。

代码如下:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
struct elephant
{
    int wei, iq, num;
} ele[1002];
int cct, dp[1002];
int cmp(const void *a, const void *b)
{
    struct elephant *aa = (struct elephant*)a;
    struct elephant *bb = (struct elephant*)b;
    return (aa->wei) - (bb->wei);
}
int DP(int i)
{
    if(dp[i] > 0)
        return dp[i];
    dp[i] = 1;
    for(int j=i+1; j<cct; ++j)
        if( (ele[j].iq < ele[i].iq)
          &&(ele[j].wei > ele[i].wei) )
        {
            int ans = DP(j) + 1;
            if(dp[i] < ans)
                dp[i] =  ans;
        }
    return dp[i];
}
void print(int i)
{
    printf("%d\n", ele[i].num + 1);
    for(int j=0; j<cct; ++j)
        if( (ele[j].iq < ele[i].iq)
          &&(ele[j].wei > ele[i].wei)
          &&(dp[i] == dp[j] + 1) )
        {
            print(j);
            break;
        }
}
int main()
{
#ifdef test
    freopen("input.txt", "r", stdin);
#endif
    cct = 0;
    while(scanf("%d%d", &ele[cct].wei, &ele[cct].iq) != EOF)
    {
        ele[cct].num = cct;
        ++cct;
    }
    memset(dp, 0, sizeof(dp));
    qsort(ele, cct, sizeof(ele[0]), cmp);

    int Max = 0, maxi;
    for(int i=0; i<cct; ++i)
    {
        int ans = DP(i);
        if(ans > Max)
        {
            Max = ans;
            maxi = i;
        }
    }
    printf("%d\n", Max);
    print(maxi);
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值