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.
InputInput 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.
OutputYour 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 1900Sample Output
4 4 5 9 7
先对重量进行排序,然后就是求最长上升子序列了,还需要记录路径,这里使用栈。
#include <cstdio>
#include <algorithm>
#include <vector>
#include <stack>
#define MAX 1001
using namespace std;
typedef struct {
int w;
int s;
int id;
} Node;
Node node[MAX];
int dp[MAX]; // dp[i]表示以a[i]结尾的最长递增子序列的长度
int n = 1;
int pre[MAX];
int cmp( Node a, Node b ) {
return a.w < b.w;
}
int main() {
int x, y;
while( scanf( "%d%d", &x, &y ) != EOF ) {
node[n].w = x;
node[n].s = y;
node[n].id = n;
n++;
}
n--;
sort( node + 1, node + 1 + n, cmp );
int Max = 0;
for( int i = 1; i <= n; i++ ) {
dp[i] = 1;
for( int j = 1; j <= i; j++ ) {
if( node[j].w < node[i].w && node[j].s > node[i].s ) {
if( dp[i] < dp[j] + 1 ) {
pre[i] = j;
dp[i] = dp[j] + 1;
}
}
}
Max = max( Max, dp[i] );
}
printf( "%d\n", Max );
for( int i = 1; i <= n; i++ ) {
if( Max == dp[i] ) {
stack<int> s;
s.push( node[i].id );
int j = i;
while( pre[j] != 0 ) {
s.push( node[pre[j]].id );
j = pre[j];
}
while( !s.empty() ) {
int cur = s.top();
s.pop();
printf( "%d\n", cur );
}
break;
}
}
return 0;
}