hdu FatMouse's Speed 动态规划DP

动态规划的解决方法是找到动态转移方程。

题目地址:http://acm.hdu.edu.cn/game/entry/problem/show.php?chapterid=3&sectionid=2&problemid=4

 

题目大意:找到一个最多的老鼠序列,使得序列中的老鼠的体重满足递增,相应老鼠的速度满足递 减。即可要求找出老鼠体重递增,速度递减的最长子序列(不需要连续).

思路:动态转移方程的确定,状态f[i]表示前i个老鼠中的最长递减子序列长度,状态转移方程为mouse[i].len = max{mouse[i].len, mouse[j].speed > mouse[i].speed} + 1, 最后找出最大的f[i]即可。

注意:此题还需要输出找到的序列中的老鼠的最原始的标号,因此不仅要在刚开始的时候把每个老鼠的最初的序号记下来,还要在进行 状态转移的时候把当前的老鼠的位置标记下来。

复制代码
 1 #include <iostream>
 2 #include<cstdio>
 3 #include<cstdlib>
 4 #include<cstring>
 5 #include<algorithm>
 6 #define Maxn 10010
 7 using namespace std;
 8 
 9 struct node{
10 int id;
11 int weight;
12 int speed;
13 int pre;
14 int len ;
15 }mouse[Maxn];
16 
17 int cmp(const struct node &a,const struct node &b)
18 {
19     if(a.weight!=b.weight)
20         return a.weight<b.weight;
21     return a.speed<b.speed;
22 
23 }
24 
25 void output(int k)
26 {
27     if(mouse[k].len==1)
28         printf("%d\n",mouse[k].id);
29     else
30     {
31         output(mouse[k].pre);
32         printf("%d\n",mouse[k].id);
33     }
34 }
35 
36 int main()
37 {
38     int cnt=0;
39     while(scanf("%d%d",&mouse[cnt].weight,&mouse[cnt].speed))
40     {
41         mouse[cnt].id=cnt+1;
42         mouse[cnt].len=1;
43         cnt++;
44     }
45     sort(mouse,mouse+cnt,cmp);
46     int i,j;
47     for(i=0;i<cnt;i++)
48         for(j=0;j<i;j++)
49     {
50         if(mouse[i].weight>mouse[j].weight&&mouse[i].speed<mouse[j].speed)//状态转移方程使用
51             if(mouse[i].len<mouse[j].len+1)
52         {
53             mouse[i].len=mouse[j].len+1;
54             mouse[i].pre=j;
55         }
56     }
57 
58 
59     int num=0;
60     for(i=0;i<cnt;i++)
61         if(mouse[num].len<mouse[i].len)
62              num=i;//记录下表
63     printf("%d\n",mouse[num].len);
64     output(num);
65     return 0;
66 
67 } 
复制代码
posted @   saucxs  阅读(756)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· [AI/GPT/综述] AI Agent的设计模式综述
点击右上角即可分享
微信分享提示