HDU-1160-FatMouse's Speed(最长单调递增子序列)

FatMouse’s Speed

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 15259 Accepted Submission(s): 6724
Special Judge

Problem Description
FatMouse believes that the fatter a mouse is, the faster it runs. To disprove this, you want to take the data on a collection of mice and put as large a subset of this data as possible into a sequence so that the weights are increasing, but the speeds are decreasing.

Input
Input contains data for a bunch of mice, one mouse per line, terminated by end of file.

The data for a particular mouse will consist of a pair of integers: the first representing its size in grams and the second representing its speed in centimeters per second. Both integers are between 1 and 10000. The data in each test case will contain information for at most 1000 mice.

Two mice may have the same weight, the same speed, or even the same weight and speed.

Output
Your program should output a sequence of lines of data; the first line should contain a number n; the remaining n lines should each contain a single positive integer (each one representing a mouse). If these n integers are m[1], m[2],…, m[n] then it must be the case that

W[m[1]] < W[m[2]] < … < W[m[n]]

and

S[m[1]] > S[m[2]] > … > S[m[n]]

In order for the answer to be correct, n should be as large as possible.
All inequalities are strict: weights must be strictly increasing, and speeds must be strictly decreasing. There may be many correct outputs for a given input, your program only needs to find one.

Sample Input
6008 1300
6000 2100
500 2000
1000 4000
1100 3000
6000 2000
8000 1400
6000 1200
2000 1900

Sample Output
4
4
5
9
7

题意:给定很多组老鼠的体重和速度,找出体重递增速度递减的最大子集。

思路:首先速度降序排列,接着求体重的最长上升子序列即可。状态转移时记录路径,最后回溯输出序号即可。

代码

#include
#include
#include
#include
using namespace std;
const int maxn=100005;
struct node
{
    int W;//升序
    int S;//降序
    int point;//下标
};
node num[maxn];
int DP[maxn];//截止到第i个数,最长单调递增子序列的长度
int path[maxn];//第i个数的上一个数是第path[i]个数
int result[maxn];//存储结果序号
bool cmp(node x,node y)
{
    if(x.S==y.S)
        return x.Wreturn x.S>y.S;
}
int main()
{
    int len=1;//数据数量
    while(scanf("%d%d",&num[len].W,&num[len].S)!=EOF)
    {
        num[len].point=len;
        len++;
    }

    sort(num+1,num+len+1,cmp);//按照S降序排列
//    for(int i=1;i
//        printf("%d***%d***%d\n",num[i].W,num[i].S,num[i].point);
//    memset(DP,0,sizeof(DP));
    memset(path,-1,sizeof(path));

    for(int i=1;i1;
    for(int i=1; ifor(int j=1; jif(num[j].Wnum[i].S&&DP[j]+1>DP[i])
            {
                DP[i]=DP[j]+1;
                path[i]=j;
            }
        }
    }
    int point=1;
    for(int i=1; iif(DP[i]>DP[point])
            point=i;


    int len_result=0;
    for(int i=point;i!=-1;i=path[i])
        result[len_result++]=num[i].point;
    printf("%d\n",DP[point]);
    for(int i=len_result-1;i>=0;i--)
        printf("%d\n",result[i]);

    return 0;
}

你可能感兴趣的:(动态规划)