gpt4 book ai didi

c++ - 分区解决太慢

转载 作者:行者123 更新时间:2023-11-28 05:55:28 24 4
gpt4 key购买 nike

我正在解决一个对我来说看起来像分区问题的问题:我有一个整数序列,我应该找到一个(如果有多个解决方案,我应该只输出一个)这些整数的子集,使得它们的总和恰好是所有整数总和的一半。

我正在尝试通过动态规划来解决它,但我的解决方案在测试中仍然太慢(我只能通过 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 是序列的大小。

关于c++ - 分区解决太慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34245505/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com