【动态规划】最长递增子序列代码(UVA 10131)

题目:http://uva.onlinejudge.org/index.php?option=onlinejudge&Itemid=8&page=show_problem&problem=1072

先按大象的体重排序,然后用DP求出大象IQ的最长递减子序列。为了输出这个子序列,每次子序列扩容时使用一个Pre[]数组保存前一个元素的索引,将索引压栈后正序输出。

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;

typedef struct elephant
{
    int weight;
    int iq;
    int index;
}ElephantType;

ElephantType Elephants[1001];
int Length[1001];
int Pre[1001];

int compare(ElephantType a, ElephantType b)
{
    if(a.weight < b.weight)
        return true;
    return false;
}

void lis(int n)
{
    int idx;
    int MaxLength;

    memset(Length, 0, sizeof(int)*1001);
    memset(Pre, 0, sizeof(int)*1001);

    Length[1] = 1;
    for(int i=2; i<=n; i++)
    {
        MaxLength = 0;
        for(int j=1; j<=i-1; j++)
        {
            if(Elephants[j].iq > Elephants[i].iq && MaxLength < Length[j])
            {
                    MaxLength = Length[j];
                    Pre[i] = j;
            }
            Length[i] = MaxLength + 1;
        }
    }
    MaxLength = 0;
    for(int i=1; i<n; i++)
        if(MaxLength < Length[i])
        {
            MaxLength = Length[i];
            idx = i;
        }
    vector<int> result;
    result.clear();

    while(Pre[idx] != 0)
    {
        result.push_back(Elephants[idx].index);
        idx = Pre[idx];
    }
    result.push_back(Elephants[idx].index);
    reverse(result.begin(), result.end());

    printf("%d\n", result.size());

    for(unsigned i=0; i<result.size(); i++)
        printf("%d\n", result[i]);
}

int main()
{
    //freopen("input.txt", "r", stdin);
    int length = 0;

    while(scanf("%d %d", &Elephants[length].weight, &Elephants[length].iq)!=EOF)
    {
        Elephants[length].index = length + 1;
        length++;
    }
    sort(Elephants+1, Elephants+length+1, compare);
    lis(length);

    return 0;
}


你可能感兴趣的:(【动态规划】最长递增子序列代码(UVA 10131))