动态规划练习二:HDU 1160 FatMouse's Speed
归根结底是dp的题目。一开始写完代码提交时wa。一直以为我的是没有错误的,现在也没搞明白为什么我原来的那个会有错误。
在论坛中取经后,在我原来的代码基础上加了一个用于跟踪路径的route数组。这样就可以保证肯定正确了。
代码如下,注释参见code。
其实排序部分完全可以用泛型算法如下:
在论坛中取经后,在我原来的代码基础上加了一个用于跟踪路径的route数组。这样就可以保证肯定正确了。
代码如下,注释参见code。
Code
其实排序部分完全可以用泛型算法如下:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef struct mouse
{
int no; //序号,从1开始计数
int weight; //存储老鼠重量
int speed; //存储老鼠速度
}mouse;
//比较函数
bool compare(const mouse &m1,const mouse &m2)
{
if(m1.weight != m2.weight)
return m1.weight < m2.weight;
return m1.speed > m2.speed;
}
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("in.txt","r",stdin);
#endif
int *F;
int *route; //用来保存路径
int *index;
int n = 1;
int i,j,k;
int weight,speed;
int max; //存储最长子序列长度
int end; //最长子序列在原序列中结束时的下标,用于反遍历route数组,得到index数组
vector<mouse> mousevec;
mouse m;
//输入
while(cin>>weight>>speed)
{
m.no = n;
m.weight = weight;
m.speed = speed;
mousevec.push_back(m);
n++;
}
//排序
sort(mousevec.begin(),mousevec.end(),compare);
//DP计算F数组
n--;
F = new int[n];
route = new int[n];
//初始化route和F数组
for(i = 0;i < n;++i)
{
route[i] = i;
F[i] = 1;
}
max = 1;
for(i = 1;i < n;++i)
{
for(j = 0;j < i;++j)
{
if(mousevec[j].weight < mousevec[i].weight && mousevec[j].speed > mousevec[i].speed)
{
if(F[j]+1 > F[i])
{
F[i] = F[j] + 1;
route[i] = j;
}
}
}
if(F[i] > max)
{
max = F[i];
end = i;
}
}
cout<<max<<endl;
index = new int[max];
for(i = 0;i < max;++i)
{
index[i] = end;
end = route[end];
}
for(i = max-1;i >= 0;--i)
cout<<mousevec[index[i]].no<<endl;
return 0;
}
#include <vector>
#include <algorithm>
using namespace std;
typedef struct mouse
{
int no; //序号,从1开始计数
int weight; //存储老鼠重量
int speed; //存储老鼠速度
}mouse;
//比较函数
bool compare(const mouse &m1,const mouse &m2)
{
if(m1.weight != m2.weight)
return m1.weight < m2.weight;
return m1.speed > m2.speed;
}
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("in.txt","r",stdin);
#endif
int *F;
int *route; //用来保存路径
int *index;
int n = 1;
int i,j,k;
int weight,speed;
int max; //存储最长子序列长度
int end; //最长子序列在原序列中结束时的下标,用于反遍历route数组,得到index数组
vector<mouse> mousevec;
mouse m;
//输入
while(cin>>weight>>speed)
{
m.no = n;
m.weight = weight;
m.speed = speed;
mousevec.push_back(m);
n++;
}
//排序
sort(mousevec.begin(),mousevec.end(),compare);
//DP计算F数组
n--;
F = new int[n];
route = new int[n];
//初始化route和F数组
for(i = 0;i < n;++i)
{
route[i] = i;
F[i] = 1;
}
max = 1;
for(i = 1;i < n;++i)
{
for(j = 0;j < i;++j)
{
if(mousevec[j].weight < mousevec[i].weight && mousevec[j].speed > mousevec[i].speed)
{
if(F[j]+1 > F[i])
{
F[i] = F[j] + 1;
route[i] = j;
}
}
}
if(F[i] > max)
{
max = F[i];
end = i;
}
}
cout<<max<<endl;
index = new int[max];
for(i = 0;i < max;++i)
{
index[i] = end;
end = route[end];
}
for(i = max-1;i >= 0;--i)
cout<<mousevec[index[i]].no<<endl;
return 0;
}
我没有什么雄心壮志,我只想给自己和关心自己的家人和朋友一个交代,仅此而已。