动态规划-活动选择
Dynamic Programming - Activity Selection
我是c++新手。有人可以把这个算法转换成一个c++代码。我不能完全理解它,谢谢。
我能够在纸上解决这个问题,使用表矩阵,我理解它的分而治之策略,但在将s和f数组传递给DP函数后实现算法有困难。
for i =1 to n
do m[i] = max(m[i-1], 1+ m [BINARY-SEARCH(f, s[i])])
We have P(i] = 1 if activity i is in optimal selection, and P[i] = 0
otherwise
i = n
while i > 0
do if m[i] = m[i-1]
then P[i] = 0
i = i - 1
else
i = BINARY-SEARCH (f, s[i])
P[i] = 1
到目前为止,我已经能够用贪婪算法做到这一点,
void MaxActGreedy(int s[], int f[], int n)
{
cout<<"n Entering Greedy Programming Function n";
clock_t startTime = clock();
cout<<" Greedy Solution (Index no. ) :";
int i;
int j;
i=0;
cout<<i;
for(j=1; j<n; j++)
{
if (s[j]>=f[i])
{
cout<<j;
i=j;
}
}
clock_t endTime= clock();
endTime = endTime - startTime;
float timeinSeconds = endTime / (float) CLOCKS_PER_SEC;
cout<<"n Greedy Time: ";
cout<<timeinSeconds;
cout<<" Seconds";
}
void Dynamic(int s[],int f[],int n)
{
int m[]={0};
for(int i=0; i<n; i++)
{
}
}
int main()
{
int s[]={1,3,0,5,3,5,6,8,8,2,12};//Start Time Si
int f[]={4,5,6,7,8,9,10,11,12,13,14};//Finish Times fi (sorted)
int n = sizeof(s)/sizeof(s[0]);
MaxActGreedy(s,f,n);
// MaxActDP(s,f,n);
Dynamic(s,f,n);
return 0;
}
我不是在实现您的伪代码,我只是在向您展示如何在c++中实现它。一种可能是:
// ...
// Declarations, prototypes, header file inclusions, ...
// ...
for (int i=1; i<=n; i++)
{
m[i] = max(m[i-1], 1+ binarySearch(f, s[i]));
if (activity_is_in_optimal_selection(i))
P[i] = 1;
else
P[i] = 0;
i = n;
while (i>0)
{
if (m[i]==m[i-1])
{
P[i] = 0;
i--;
}
else
{
i = binarySearch(f, s[i]);
P[i] = 1;
}
}
}
我不确定我是否理解你的算法,但是打开你的IDE并开始编写程序。
相关文章:
- 如何使用默认参数等选择模板专业化
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 选择要调用的构造函数
- C++选择排序算法中的逻辑错误
- QTreeView幻灯片多选后无法使用单击选择
- 无法获取菜单选择以运行函数.C++
- Qt C++静态thread_local QNetworkAccessManager是线程应用程序的好选择吗
- 在C++中,如何通过几种类型从元组中选择多个元素
- 讨论 - 创建矩阵时的数组与向量的向量 - 什么是最实用的选择
- 对可变参数使用声明.如何选择正确的功能
- 选择选举获胜者的程序
- 如何选择在 csv 文件中输出的位置
- 根据用户回答声明"Players"。用户选择玩家数量。播放器是结构体
- 程序在尝试猜测它选择的随机数时进入无限循环?
- 选择和修改嵌套向量中的条目的最佳实践
- 在PostgreSQL中根据它们的ID选择大量行的最快方法是什么?
- 使用动态编程以有限的资金选择活动
- Delphi / C 构建器 - 在TDBGrid中设置活动 /选择的行颜色
- 如何在不破坏非活动选择颜色的情况下更改 wxTextCtrl 的背景颜色
- 动态规划-活动选择