如何解决计算具有k个部分的整数部分,每个部分低于某个阈值m
我想计算将数字n
划分为k
个不同部分(其中每个部分都不大于m
)的方法的数量。
对于k := 2
,我有以下算法:
public int calcIntegerPartition(int n,int k,int m) {
int cnt=0;
for(int i=1; i <= m;i++){
for(int j=i+1; j <= m; j++){
if(i+j == n){
cnt++;
break;
}
}
}
return cnt;
}
但是我如何用k > 2
计算整数分区?通常我有n > 100000
,k := 40
,m < 10000
。
谢谢。
解决方法
让我们开始选择k个最大的合法数字:m,m-1,m-2,...,m-(k-1)。这总计为k * m-k(k-1)/ 2。如果m
让我们说p =(k m-k (k-1)/ 2)-n。
如果p =0。请注意,如果p = 0,则只有一个解,所以假设p> 0。
现在,假设我们从选择k个最大的不同合法整数开始,然后我们对其进行更正以获得解决方案。我们的校正包括将值向左(在数字行上)移动1个插槽到空插槽,恰好是p次。我们有多少种方法可以做到这一点?
开头的最小值是m-(k-1),它可以向下移动多达1,因此最多可以移动m-k次。此后,每个连续的值都可以向上移动到其先前的移动。
现在的问题是,有多少个m-k最大值的非递增整数序列求和为p?这是分区问题。即,我们可以将p划分为多少种方法(最多分为k个分区)。这不是封闭形式的解决方案。
有人已经在这里为这个问题写了一个很好的答案(需要稍加修改以满足您的限制):
Is there an efficient algorithm for integer partitioning with restricted number of parts?
,正如@Dave所暗示的那样,对于简单的受限整数情况(在这里(与@Dave相同的链接):Is there an efficient algorithm for integer partitioning with restricted number of parts?)已经有了一个非常好的答案。
以下是.globl _start
中的一个变体,它考虑了每个受限制部分的最大值。首先,这是主力军:
C++
如您所见,#include <vector>
#include <algorithm>
#include <iostream>
int width;
int blockSize;
static std::vector<double> memoize;
double pStdCap(int n,int m,int myMax) {
if (myMax * m < n || n < m) return 0;
if (myMax * m == n || n <= m + 1) return 1;
if (m < 2) return m;
const int block = myMax * blockSize + (n - m) * width + m - 2;
if (memoize[block]) return memoize[block];
int niter = n / m;
if (m == 2) {
if (myMax * 2 >= n) {
myMax = std::min(myMax,n - 1);
return niter - (n - 1 - myMax);
} else {
return 0;
}
}
double count = 0;
for (; niter--; n -= m,--myMax) {
count += (memoize[myMax * blockSize + (n - m) * width + m - 3] = pStdCap(n - 1,m - 1,myMax));
}
return count;
}
与链接的解决方案非常相似。一个明显的区别是顶部的2个附加检查:
pStdCap
这是设置递归的函数:
if (myMax * m < n || n < m) return 0;
if (myMax * m == n || n <= m + 1) return 1;
参数说明:
-
double CountPartLenCap(int n,int myMax) { if (myMax * m < n || n < m) return 0; if (myMax * m == n || n <= m + 1) return 1; if (m < 2) return m; if (m == 2) { if (myMax * 2 >= n) { myMax = std::min(myMax,n - 1); return n / m - (n - 1 - myMax); } else { return 0; } } width = m; blockSize = m * (n - m + 1); memoize = std::vector<double>((myMax + 1) * blockSize,0.0); return pStdCap(n,m,myMax); }
是您要分区的整数 -
n
是每个分区的长度 -
m
是给定分区中可以出现的最大值。 (OP将其称为阈值)
这是现场演示https://ideone.com/c3WohV
这是myMax
的非记忆版本,较容易理解。最初是在对Is there an efficient way to generate N random integers in a range that have a given sum or average?
pStdCap
如果您实际上打算计算多达10000个数字的分区数,则将需要一个int pNonMemoStdCap(int n,int myMax) {
if (myMax * m < n) return 0;
if (myMax * m == n) return 1;
if (m < 2) return m;
if (n < m) return 0;
if (n <= m + 1) return 1;
int niter = n / m;
int count = 0;
for (; niter--; n -= m,--myMax) {
count += pNonMemoStdCap(n - 1,myMax);
}
return count;
}
大int库(基于OP的要求)。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。