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.
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.
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.
6008 1300 6000 2100 500 2000 1000 4000 1100 3000 6000 2000 8000 1400 6000 1200 2000 1900
4 4 5 9 7
这道题错了很多次才过,其实这道题的思路很简单很容易想,就是先排序再dp,我主要实忽略了很多细节。细节真的很重要。
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<iostream>
#include<algorithm>
#include<string>
#include<stack>
int INF=0x3f3f3f3f;
using namespace std;
int dp[1005],pre[1005];
struct Node
{
int w,v,num;
}node[1005];
bool cmp(Node a,Node b) //先按重量由小到大排序,再按速度由大到小排序
{
return a.w<b.w;
if(a.w==b.w)
return a.v>b.v;
}
int main()
{
// freopen("E:\\file.txt","r",stdin);
int w1,v1,i=1;
while(scanf("%d%d",&w1,&v1)!=EOF)
{
node[i].w=w1,node[i].v=v1;
node[i].num=i;
i++;
}
int n=i-1; //个数
sort(node+1,node+i,cmp); //排序从小到大
int Max=0,mark;
for(int j=1;j<=n;j++)
{
dp[j]=1;
pre[j]=0;
for(int k=1;k<j;k++) //和j前面的相比较
{
if(node[j].w>node[k].w&&node[j].v<node[k].v&&dp[j]<dp[k]+1) //只有当前的小于它前面的时候才把k赋值给next1 和它前面的相比 其重量增加但是它的速度要减小
{
dp[j]=dp[k]+1; //如果减小的话 我们就让它dp的值选择大的
pre[j]=k; //让它的上一个的值保存
}
}
if(dp[j]>Max)
{
Max=dp[j];
mark=j;
}
}
cout<<Max<<endl; //输出最大值
stack<int> s;
s.push(node[mark].num);
int k=mark;
while(pre[k]!=0)
{
int q=pre[k];
s.push(node[q].num);
k=pre[k];
}
while(s.size()!=0)
{
int q=s.top();
cout<<q<<endl;
s.pop();
}
return 0;
}