HDU1160FatMouse's Speed(DP)

题目链接:传送门biubiubiu···

分析:题意大概是有若干只老鼠的数据,要找到最大的子序列将他们按照体重从大到小,速度从小到大的顺序输出。记录路径的话在结构数组中开个n记录原始的顺序,然后再用一个l来记录每一个数据的上一个数据,运用dp求出最大的序列。

AC代码:

#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int INF=10000000;
struct mouse{
	int w,s,n,l;	//n是记录原来顺序,l记录某个数据连接的上一个数据
}mice[1005];
int dp[1005];
bool cmp(mouse a,mouse b){		//排序按照体重从大到小排
	if(a.w==b.w)	return a.s<b.s;
	else return a.w>b.w;
}
int main(){
	int c=1;
	while(scanf("%d%d",&mice[c].w,&mice[c].s)!=EOF){
		mice[c].n=c;
		mice[c++].l=0; 	//初始化都为0
	}
	sort(mice+1,mice+1+c,cmp);
	mice[0].l=0;
	mice[0].n=0;
	mice[0].s=0;
	mice[0].w=INF;
	dp[0]=0;
	int ans=0;	//用来记录最大序列的最后一个数
	for(int i=1;i<c;i++){
		dp[i]=0;
		for(int j=0;j<i;j++){
			if(mice[i].w<mice[j].w&&mice[i].s>mice[j].s&&(dp[i]<=dp[j]+1)){
					dp[i]=dp[j]+1;	
					mice[i].l=j;	//mark一下此数据连接的上一个数据
					if(dp[i]>dp[ans])	ans=i;
			}
		}	
	} 
	cout<<dp[ans]<<endl;
	while(mice[ans].l!=0){
		cout<<mice[ans].n<<endl;
		ans=mice[ans].l;
	}
	cout<<mice[ans].n;
}

猜你喜欢

转载自blog.csdn.net/weixin_43556295/article/details/88123722