FatMouse's Speed HDU - 1160 最长上升子序列

xiaoxiao2021-02-28  96

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

只需要对速度降序排列,这就是一个最长上升子序列问题,但是需要记录一下路径,与并查集相同,利用pre数组表示当前节点的头结点是什么,最后递归打印一下路径即可。

#include<bits/stdc++.h> using namespace std; struct aa { int pos,wei,spd; } save[1086]; struct bb { int len,pre,val; } dp[1086]; bool cmp(const aa &a,const aa &b) { return a.spd>b.spd; } void findboss(int s) { if(s==-1) return ; findboss(dp[s].pre); printf("%d\n",dp[s].val); } int main() { int cnt=0; while(scanf("%d%d",&save[cnt].wei,&save[cnt].spd)!=EOF) { save[cnt].pos=cnt+1; cnt++; } sort(save,save+cnt,cmp); int fpos,mlen=0; for(int i=0; i<cnt; i++) { int maxlen=0,pos=-1; dp[i].val=save[i].pos;//数值就是之前数组的位置下标 for(int j=i-1; j>=0; j--) { if(save[j].wei<save[i].wei&&dp[j].len>maxlen)//没他重的最长情况 { maxlen=dp[j].len; pos=j;//记录路径 } } dp[i].pre=pos,dp[i].len=maxlen+1; if(dp[i].len>mlen)//筛选最大值 { mlen=dp[i].len; fpos=i; } } printf("%d\n",mlen); findboss(fpos);//递归打印 }

转载请注明原文地址: https://www.6miu.com/read-76912.html

最新回复(0)