您的位置:首页 > 其它

hdu 1160 FatMouse's Speed(最大上升子序列+路径输出)

2016-01-20 18:12 190 查看

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
then it must be the case that

W[m[1]] < W[m[2]] < ... < W[m
]

and

S[m[1]] > S[m[2]] > ... > S[m
]

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


原题的样例输出有点问题,正确的应该是4 4 5 9 8,以为自己写的不对,找了好长时间debug,后来用网上的代码ac了,发现原来是样例数据错了。

题解:先把数据排序(先按照体重从小到大排序,体重相同的再按照速度从大到小排序),这样题目就转换成了求最大上升子序列并输出路径。



注意要认真理解体会,其实并不复杂。

#include <iostream>
#include <memory.h>
#include <algorithm>
#include <stdio.h>
#define NUM 1010
#define INF 0x3f3f3f3f

using namespace std;

int flag;  //最大上升子序列的最末尾元素下标
int dp[NUM];//dp[i]代表以第i个数据结尾的最大上升子序列的序列长度
int path[NUM];//path[i]用来存储以第i个元素结尾的最大上升子序列的前驱标号
int re[NUM];//用来存储最大上升子序列的下标,记得要倒序输出

struct Mouse
{
int w;//重量
int s;//速度
int index;//记录数据初始顺序
}m[NUM];

int cmp(Mouse a,Mouse b)
{
if(a.w==b.w)
return a.s>b.s;
return a.w<b.w;
}

int main()
{
int num=1;
while(cin>>m[num].w>>m[num].s)
{
m[num].index=num;
num++;
}
num--;
sort(m+1,m+1+num,cmp);
memset(dp,0,sizeof(dp));
memset(path,0,sizeof(path));
dp[1]=1;
for(int i=2;i<=num;i++)
{
for(int j=1;j<i;j++)
{
if(m[j].w<m[i].w&&m[j].s>m[i].s)
{
if(dp[i]<dp[j])
{
dp[i]=dp[j];
path[i]=j;
}
}
}
dp[i]++;
}
int Max=-1;
for(int j=1; j<=num; j++)
{
if(Max<dp[j])
{
Max=dp[j];
flag=j;
}
}
cout<<Max<<endl;
cout<<"flag:"<<flag<<endl;
for(int i=1;i<=num;i++)
{
printf("path[%d]:%d   m[%d]:%d\n",i,path[i],i,m[i].index);
}
int e=0;
while(flag)  //将标号存入re数组
{
re[e++]=flag;
flag=path[flag];
}
while(e)  //倒序输出
{
e--;
cout<<m[re[e]].index<<endl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: