分区解决方案太慢
Partition solution too slow
我正在解决一个看起来像分区问题的问题:我有一个整数序列,我应该找到这些整数的一个子集(如果有多个解决方案,我应该只输出一个),这样它们的和正好是所有整数和的一半。
我试图通过动态编程来解决它,但我的解决方案在测试中仍然太慢(我只能通过2/10测试,其余的太慢)。谢谢你的帮助。
我的代码:
void split(std::vector<int> seq, int sum, FILE * output){
int n = seq.size() + 1;
int m = sum + 1;
bool** matrix = (bool**)malloc(m*sizeof(bool*));
for(int i = 0;i<m;i++){
matrix[i] = (bool*)malloc(n*sizeof(bool));
}
for(int i=1;i<=m-1;i++){
matrix[0][i]=false;
}
for(int i=0;i<=n-1;i++){
matrix[i][0]=true;
}
for(int i=1;i<=n-1;i++){
for(int j=1;j<=m-1;j++){
matrix[i][j] = matrix[i-1][j];
if(matrix[i][j]==false && j>=seq[i-1])
matrix[i][j] = matrix[i][j] || matrix[i-1][j-seq[i-1]];
}
}
if(matrix[n-1][m-1]){
int row = n-1;
int column = m-1;
while((row > 1) && (column > 0)){
while(matrix[row-1][column]){row--;}
fprintf(output, "%i ", row);
column = column - seq[row-1];
}
}
else{
fprintf(output, "no");
}
}
如果允许其他方法,您可以尝试使用二进制搜索树。它应该在O(n log n)时间内完成,其中n是序列的大小。
相关文章:
- 运行同一解决方案的另一个项目的项目
- Project Euler问题4的错误解决方案
- 计算每个节点的树高,帮助我解释这个代码解决方案
- C++:Application.cpp中抛出了未解析的外部符号(解决方案在问题的末尾,供未来的读者参考)
- visual c++,如何获取解决方案目录中的代码
- 有没有办法在远程设备上打开和编辑visual Studio 2017解决方案
- C++Matching Brackets 2解决方案不起作用
- 在 ubuntu3 上C++ goto 定义有什么解决方案吗16.04?
- 在 leetcode 上提交解决方案时出现堆栈缓冲区溢出错误
- 我的固定时间步长与增量时间和插值的解决方案是错误的吗?
- 无法在问题解决方案中执行输出逻辑
- 最大的回文产品 - 程序未运行,编写解决方案但无法理解问题
- 从预序遍历构造 bst 的 c++ 和 python 解决方案之间的区别
- 在一个解决方案中针对第三方静态库 (Creo) 的不同版本(版本)进行构建
- 如何巧妙地编写两个函数——一个用于检查是否存在解决方案,另一个用于获取所有解决方案
- 使用 Git 处理 C++ Visual Studio 2019 解决方案的外部依赖项源代码管理的最佳方法是什么?
- N-queen问题:无法弄清楚为什么我的解决方案不起作用
- 从排序数组中删除重复项,具有不同代码方式的相同解决方案具有不同的输出
- 在一个应用程序中MPI_Scatter和MPI_Bcast解决方案。如何让分区打印分区大小
- 分区解决方案太慢