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
解题思路:
因为要满足的条件是 “质量增大 , 速度减小”
所以首先通过排序,将其中一个条件定下来(按照质量从小到大排序,若质量相同,速度从大到小排序)
排完序之后,问题就变成了求最大递减子序列问题了(详解)。
注意:需要输出具体的路径,本题借助了pre数组来实现。
代码:
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef struct{
int size;
int speed;
int id;
}Mouse;
bool method(Mouse a , Mouse b){
if(a.size != b.size){
return a.size < b.size;
}else{
return a.speed > b.speed;
}
}
Mouse ms[1010];
int pre[1010];
int dp[1010];
int ans[1010];
int main(){
//freopen("D://testData//1160.txt" , "r" , stdin);
int si , sp , i = 0;
int j , k , maxnum = 0 , curr = 0 ;
while(scanf("%d %d",&si , &sp) != EOF){
ms[i].id = i;
ms[i].size = si;
ms[i++].speed = sp;
}
sort(ms , ms + i , method);
memset(pre , -1 , sizeof(pre));
memset(dp , 0 , sizeof(dp));
for(j = 0 ; j < i ; j ++){ //DP
for(k = 0 ; k < j ; k ++){
if(ms[j].speed < ms[k].speed && ms[j].size > ms[k].size){
if(dp[k] + 1 > dp[j]){
pre[j] = k;
dp[j] = dp[k] + 1;
if(dp[j] > maxnum)
maxnum = dp[j];
}
}
}
}
printf("%d\n",maxnum + 1);
//寻找路径,并记录在ans数组中
for(j = i-1 ; j >= 0 ; j --){
if(dp[j] == maxnum){
curr = j;
break;
}
}
k = 0;
while(curr != -1){
ans[k ++] = curr;
curr = pre[curr];
}
for(j = k - 1 ; j >= 0 ; j --){
printf("%d\n",ms[ans[j]].id + 1);
}
return 0;
}