FatMouse's Speed HDU

来源:互联网 发布:淘宝身高体重尺码表 编辑:程序博客网 时间:2024/05/18 08:37
最长上升子序列 + 打印路径
题目描述:找最长的老鼠序列要求,后面的老鼠体重比前面的打,速度比前面的小,求这个最长序列的长度,并输出老鼠序列。
解题分析:此题需要排序,之后按照最长上升子序列并打印路径就行了。

代码如下:

#include <iostream>#include <cstdio>#include <algorithm>#include <cstring>using namespace std;const int maxn = 1000 + 10;struct Node{    int w,s,id;    bool operator <(const Node &b)const    {        return w < b.w || w == b.w && s > b.s;    }}M[maxn];int path[maxn];int dp[maxn];void print(int i){    if(path[i] == -1)    {        printf("%d\n",M[i].id);        return;    }    else    {        print(path[i]);        printf("%d\n",M[i].id);    }}int main(){    int cnt = 1;    while(scanf("%d %d",&M[cnt].w,&M[cnt].s)!=EOF)    {        M[cnt].id = cnt;        cnt++;    }    memset(path,-1,sizeof(path));    sort(M + 1,M + cnt + 1);    for(int i = 1; i <= cnt; i++)    {        dp[i] = 1;        for(int j = 1; j < i; j++)        {            if(M[i].w > M[j].w && M[i].s < M[j].s)            {                if(dp[i] < dp[j] + 1)                {                    dp[i] = dp[j] + 1;                    path[i] = j;                }            }        }    }    int index = -1;    int ans = -1;    for(int i = 1; i <= cnt; i++)    {        if(dp[i] > ans)        {            ans = dp[i];            index = i;        }    }    cout << ans << endl;    print(index);    return 0;}