首页 > 代码库 > HDU 1160 FatMouse's Speed (最长上升子序列+记录路径)

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

题目链接:HDU 1160 FatMouse‘s Speed

题意:求体重越重,反而速度越慢的例子,并输出对应的编号。

对speed进行从大到小排序,再求weight的最长上升序列,并输出路径。


AC代码:


#include<stdio.h>
#include<algorithm>
#include<stack>
using namespace std;
struct Node
{
	int weight;
	int speed;
	int id;
};
struct Node p[1010];

bool cmp(Node a,Node b)
{
	if(a.speed!=b.speed)
		return a.speed>b.speed;
	return a.weight<b.weight;
}
int main()
{
	int n,j,i,w,s;
	int dp[1010],record[1010];
	n=0;
	while(scanf("%d %d",&w,&s)!=EOF)
	{
		n++;
		p[n].weight=w;
		p[n].speed=s;
		p[n].id=n;
	}
	sort(p+1,p+n+1,cmp);
	for(i=1;i<=n;i++)
		dp[i]=1;
	int maxlen=1,max_i=1;
	for(i=1;i<=n;i++)
	{
		int max=0,max_j=1;
		for(j=1;j<i;j++)
		{
			if(p[j].weight<p[i].weight && dp[j]>max)
			{
				max=dp[j];
				max_j=j;
			}
		}
		dp[i]=max+1;
		record[i]=max_j;
		if(dp[i]>maxlen)
		{
			maxlen=dp[i];
			max_i=i;
		}
//		printf("%d %d\n",p[max_j].weight,max_j);
	}
	printf("%d\n",maxlen);
	stack<int> ss;
	while(!ss.empty()) ss.pop();
	for(i=maxlen;i>0;i--)
	{
		ss.push(max_i);
		max_i=record[max_i];
	}
	while(!ss.empty())
	{
		printf("%d\n",p[ss.top()].id);
		ss.pop();
	}
return 0;
}


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