问题:
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.
大意:
每行给你两个数据,体重和速度,一直输入到文件结束为止。从中找最多的数据严格按照体重增加,速度减小排列,输出这些数据个数,然后输出排列好的顺序,(符合条件的可能有多种,输出一种即可)
思路:
1:我们可以先把一个排好序,然后再按求最长上升子序列系的求法。
2:如何输出路径是关键,设c[ i ]=[ j ]为从 j 到 i 当满足题意时把 i 添加进 j 的序列里。即路径为 j -> i 。
代码:
#define N 1010
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
int n;
int dp[N],c[N];
struct node
{
int w,s,ii;
} k[N];
bool cmp(node x,node y)
{
if(x.w==y.w)
return x.s>y.s;
else
return x.w<y.w;
}
int main()
{
n=0;
while(cin>>k[n].w>>k[n].s)
{
k[n].ii=n;
n++;
}
sort(k,k+n,cmp);//首先按体重排,这个代码如果先按速度排是不正确的
memset(c,0,sizeof(c));
int d=0,flag=0;
for(int i=0; i<n; i++)//求最长上升子序列
{
dp[i]=1;
for(int j=0; j<i; j++)
{
if(k[j].w<k[i].w&&k[j].s>k[i].s&&dp[j]+1>dp[i])
{
dp[i]=dp[j]+1;
c[i]=j;//储存路径
if(dp[i]>d)//保留最长的路径
{
flag=i;
d=dp[i];
}
}
}
}
int dc[N],dd=0;
while(flag)//保留最长的路径
{
dc[dd++]=flag;
flag=c[flag];
}
cout<<dd<<endl;
for(int i=dd-1; i>=0; i--)//输出未排序之前的下标路径
cout<<k[dc[i]].ii+1<<endl;//
return 0;
}