FatMouse's Speed

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

给定 n 只老鼠,每只老鼠有体重和速度,求老鼠的一个最长序列,使得体重严格递增,速度严格递减。给出这个序列的长度,并且输出这个序列中的每只老鼠在输入中的序号。


解题思路:先对所有老鼠排序,第一个关键字体重从小到大,第二关键字速度从大到小。然后求这个序列中的最长严格递增子序列


dp[i] 记录以 i 只老鼠作为结尾的最长合法序列的长度,则有状态转移方程 dp[i]=max{dp[j]+1},0<=j<i, 只老鼠前面。


#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
using namespace std;
const int N = 1005;
struct node{
	int w;
	int v;
	int id;
}arr[N];
int dp[N];
void init(){
	for(int i=0;i<N;i++){
		dp[i]=1;
		arr[i].id=i;
	}
}
int cmp(node a,node b){
	if(a.w==b.w) return a.v<b.v;
	return a.w<b.w;
}
int main(){
	init();
	int id=1,x,y;
	while(scanf("%d%d",&x,&y)!=EOF){
		arr[id].w=x;
		arr[id].v=y;
		id++;
	}
	sort(arr+1,arr+id,cmp);
	int maxt=1;
	for(int i=2;i<id;i++){
		for(int j=1;j<i;j++){
			if(arr[j].w<arr[i].w&&arr[j].v>arr[i].v){
				dp[i]=max(dp[j]+1,dp[i]);
				if(dp[i]>dp[maxt])
				  maxt=i;
			}
		}
	}
	printf("%d\n",dp[maxt]);
	int temp=maxt;
	vector<int>G;
	G.push_back(maxt);
	for(int i=maxt-1;i>=1;i--){
		if(dp[maxt]==dp[i]+1){
			G.push_back(i);
			maxt=i;
		}
	}
	for(int i=dp[temp]-1;i>=0;i--)
	   printf("%d\n",arr[G[i]].id);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/islittlehappy/article/details/80353707
今日推荐