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.
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1160
这道题的意思是输入一些老鼠的体重和奔跑速度,然后找到一个最多的老鼠序列,使得序列中的老鼠的体重满足递增,相应老鼠的速度满足递减。
思路是先按体重递增排序,然后按体重寻找最大递增子序列,但同时也要满足速度是递减的。
#include <iostream>
#include<stdio.h>
#include<algorithm>
using namespace std;
int dp[1005];
struct node
{
int w, s, n;
}a[1005];
int cmp(node a, node b)//按体重递增排序,如果体重相同,那么速度快的排前面。
{
if (a.w == b.w) return a.s > b.s;
else return a.w < b.w;
}
int main()
{
int k = 1;
while (scanf("%d %d", &a[k].w, &a[k].s) != EOF)//输入数据
{
a[k].n = k;
k++;
}
k--;
sort(a + 1,a + k, cmp);
int maxn = 0;
for (int i = 1; i <= k; i++)
dp[k] = 1;
for (int i = k; i >=0; i--)//状态转移方程
for(int j=i+1;j<=k;j++)
if (a[j].w > a[i].w&&a[j].s < a[i].s)
{
dp[i] = max(dp[j] + 1, dp[i]);
if (dp[i] > maxn) maxn = dp[i];
}
cout << maxn+1<<endl;
int temp = maxn;
for (int i = 1; i <= k; i++)//进行动态规划时已经把到每个老鼠的最大递增子序列记录上了,
所以现在只需要依次把最大递增子序列的老鼠数据输出就行了。
{
if (dp[i] == temp)
{
cout << a[i].n << endl;
temp--;
}
}
}