分而治之的动态规划
Dynamic Programming to Divide and Conquer
我正在研究这个将分治算法转换为动态规划算法的程序。该算法是用于测序(如DNA)并找出这样做的成本。只是重申一下动态规划算法是有效的,而分治法不是,我不知道为什么。
#include<iostream>
#include <vector>
using namespace std;
int penalty;
int m, n;
char x[] = { 'A', 'A', 'C' }; //, 'A', 'G', 'T', 'T', 'A', 'C', 'C' };
char y[] = { 'T', 'A' }; //,'A' //, 'G', 'G', 'T', 'C', 'A' };
//find minimum
int min(int one, int two, int three)
{
if (one <= two && one <= three)
return one;
if (two <= one && two <= three)
return two;
return three;
}
//divide and conquer way of find the cost of the optimal path
int optMethod(int i, int j)
{
if (i == m)
return 2 * (n - j);
else if (j == n)
return 2 * (m - i);
else {
if (x[i] == y[j])
penalty = 0;
else
penalty = 1;
return min(optMethod(i + 1,j + 1) + penalty, optMethod(i + 1,j) + 2, optMethod(i,j + 1) + 2);
}
}
//dynamic programming way of finding cost of optimal path
void dynamicOptimal(vector<vector<int>>& opt1) {
for (int i = m; i >= 0; i--) {
for (int j = n; j >= 0; j--) {
if (i == m)
opt1[m][j] = 2 * (n - j);
else if (j == n)
opt1[i][n] = 2 * (m - i);
else {
if (x[i] == y[j])
penalty = 0;
else
penalty = 1;
opt1[i][j] = min(opt1[i+1][j+1] + penalty, opt1[i+1][j] + 2, opt1[i][j+1] + 2);
}
}
}
}
int main() {
m = sizeof(x);
n = sizeof(y);
//divide and conquer
cout << optMethod(0, 0) << endl;
//dynamic
vector <vector<int> > optimal(m+1, vector<int>(n+1, 0));
dynamicOptimal(optimal);
cout<<optimal[0][0]<<endl;
cin.get();
return 0;
}
我现在得到的是有一个额外的惩罚,但我不知道在哪里。我知道我没有使用std::min,我知道它在那里
你应该改变:
if (two <= one && two <= two)
return two;
return three;
:
if (two <= one && two <= three)
return two;
return three;
相关文章:
- C++ 分而治之的算法问题
- 如何解决动态规划问题?
- 使用分而治之的最大总和子数组,为什么要以不同的方式使用 for 循环,答案是错误的?
- 如何将这种递归解决方案转换为分而治之?
- 最接近的一对点 用向量分而治之
- 通过分而治算法计算数组的最大数量
- 通过分而治之查找子字符串
- 分而治之合并排序不起作用
- 分而治之数组算法++
- 分而治之和分叉和加入的区别
- 用于查找多数元素的分而治之算法
- 斐波那契 - 分而治之算法
- 为什么这个计数器以这种方式增加,而不是在这个分而治之算法中一个接一个地增加
- C++ 递归排序通过分而治之和迭代排序
- 使用分而治之搜索字符串中'xy'的第一个索引
- 使用分而治之的二进制到十进制转换
- 分而治之真的能战胜增加的内存分配吗
- 分而治之的动态规划
- 使用分而治之对矩阵中的元素进行计数
- 分而治之-C/C++库函数和运算符是最理想的函数和运算符吗