FatMouse's Speed(最长上升子序列+路径记录)

Time limit   1000 ms

Memory limit   32768 kB

Special judge   Yes 

OS   Windows

题目:

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
8

参考:最长上升子序列(LIS)

题意:给出任意只猴子的重量和速度,问最多有多少个是按照体重越轻,速度越快的递增子序列。其实就是LIS(最长上升子序列)

的一个变形,按输入数据时的顺序输出序号。先把猴子的重量,速度,序号存入结构体, 再根据重量从小到大的顺序,重量相同的条件下速度从小到大的顺序排序。根据要求(体重越轻,速度越快)求最长上升子序列。记录dp[]的最大值位置。根据子序列每两个数相差1的规律依次把序列元素存入动态数组vector中,最后按顺序输出vector中的值即可。具体看代码:

#include <stdio.h>
#include <string.h>
#include <vector>
#include <algorithm>
using namespace std;
int dp[1005];
struct mouse
{
	int weight,speed,id;
}m[1005];

bool cmp(mouse a,mouse b)
{
	if(a.weight==b.weight)
		return a.speed<b.speed;
	return a.weight<b.weight;
}

void init()
{
	for(int i=0;i<1005;i++)
	{
		m[i].id=i;
		dp[i]=1;
	}
}

int main()
{	
	init();
	int t1,t2,ad=1,maxx=1;
	vector<int>v;
	while(scanf("%d %d",&t1,&t2)!=EOF)
	{
		m[ad].weight=t1;
		m[ad].speed=t2;
		ad++;
	}

	sort(m+1,m+ad,cmp);

	for(int i=2;i<ad;i++){
		for(int j=1;j<i;j++){
			if(m[j].weight<m[i].weight&&m[j].speed>m[i].speed){
				dp[i]=max(dp[j]+1,dp[i]);
				if(dp[i]>dp[maxx])
				  maxx=i;
			}
		}
	}

	printf("%d\n",dp[maxx]);
	int temp=maxx;
	v.push_back(maxx);
	for(int i=maxx-1;i>=1;i--)
	{
		if(dp[maxx]==dp[i]+1){
			v.push_back(i);
			maxx=i;
		}
	}

	for(int i=dp[temp]-1;i>=0;i--)
	{
		printf("%d\n", m[v[i]].id);
	}


	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43301061/article/details/86525751
今日推荐