FatMouse's Speed
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 20494 Accepted Submission(s): 9085
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
动态规划寻找最长子序列问题,本题要求找出符合体重递增、速度递减的老鼠的一个最长子序列并输出老鼠的编号。
思路:
构建一个mice结构体,id存储每只老鼠的输入顺序(因为最后输出是要按照输入顺序来的),weight和speed存储每只老鼠的体重和速度,pre存储该只老鼠所在的序列中的上一只老鼠的编号,cnt存储该只老鼠在所在序列中的位置。输出时比较每条子序列的长度(即cnt),选取最大的,因为pre初始化为-1,所以每个序列开头的一直老鼠的pre值都为-1,采用递归方法输出序列。
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
struct mice {
int id;
int weight;
int speed;
int pre;
int cnt;
} m[1010];
bool cmp( mice aa , mice bb ) {
return aa.weight==bb.weight ? aa.speed<bb.speed : aa.weight<bb.weight;
}
void print( int id ) {
if( m[id].pre!=-1 )
print( m[id].pre );
printf( "%d\n",m[id].id+1 );
}
int main() {
// freopen( "in.txt","r",stdin );
// std::ios::sync_with_stdio( false );
int n,maxn,id,i,j;
i=0;
while( cin >> m[i].weight >> m[i].speed ) {
m[i].id = i;
m[i].pre = m[i].cnt = -1;
i++;
}
n = i;
sort( m,m+n,cmp );
maxn = 0;
id = -1;
for( i=0 ; i<n ; i++ ) {
if( m[i].cnt==-1 )
m[i].cnt = 0;
for( j=i+1 ; j<n ; j++ ) {
if( m[j].weight<=m[i].weight || m[j].speed>=m[i].speed )
continue;
if( m[j].cnt < m[i].cnt + 1 ) {
m[j].cnt = m[i].cnt + 1;
m[j].pre = i;
if( m[j].cnt>maxn ) {
maxn = m[j].cnt;
id = j;
}
}
}
}
printf( "%d\n",maxn+1 );
print( id );
}
6万+

被折叠的 条评论
为什么被折叠?



