我一直在关注Number of ways to write n as a sum of powers of 2,它运行得很好,但我想知道如何提高该算法的运行时效率。它无法在任何合理的时间内(10秒内)计算出大于~1000的任何东西。
我认为它与将其分解为子问题有关,但不知道如何去做。我在想O(n)或O(nlogn)运行时 - 我确信它有可能以某种方式。我只是不知道如何有效地分工。
代码来自Chasefornone
#include<iostream>
using namespace std;
int log2(int n)
{
int ret = 0;
while (n>>=1)
{
++ret;
}
return ret;
}
int power(int x,int y)
{
int ret=1,i=0;
while(i<y)
{
ret*=x;
i++;
}
return ret;
}
int getcount(int m,int k)
{
if(m==0)return 1;
if(k<0)return 0;
if(k==0)return 1;
if(m>=power(2,k))return getcount(m-power(2,k),k)+getcount(m,k-1);
else return getcount(m,k-1);
}
int main()
{
int m=0;
while(cin>>m)
{
int k=log2(m);
cout<<getcount(m,k)<<endl;
}
return 0;
}
答案 0 :(得分:3)
由于我们正在处理一些基础的权力(在这种情况下为2),我们可以在O(n)
时间(和空间,如果我们考虑固定大小的计数)轻松地做到这一点。
关键是分区的生成功能。让p(n)
为将n
写为基数b
的幂和的方法的数量。
然后考虑
∞
f(X) = ∑ p(n)*X^n
n=0
可以将f
写成无限产品,
∞
f(X) = ∏ 1/(1 - X^(b^k))
k=0
如果只想要系数达到某个限制l
,则只需要考虑b^k <= l
的因子。
以正确的顺序(降序)乘以它们,在每一步都知道只有索引可被b^i
整除的系数是非零的,所以只需要n/b^k + n/b^(k-1) + ... + n/b + n
个系数的加法,总计O(n)
。
代码(不防止更大的参数溢出):
#include <stdio.h>
unsigned long long partitionCount(unsigned n);
int main(void) {
unsigned m;
while(scanf("%u", &m) == 1) {
printf("%llu\n", partitionCount(m));
}
return 0;
}
unsigned long long partitionCount(unsigned n) {
if (n < 2) return 1;
unsigned h = n /2, k = 1;
// find largest power of two not exceeding n
while(k <= h) k <<= 1;
// coefficient array
unsigned long long arr[n+1];
arr[0] = 1;
for(unsigned i = 1; i <= n; ++i) {
arr[i] = 0;
}
while(k) {
for(unsigned i = k; i <= n; i += k) {
arr[i] += arr[i-k];
}
k /= 2;
}
return arr[n];
}
工作得足够快:
$ echo "1000 end" | time ./a.out
1981471878
0.00user 0.00system 0:00.00elapsed
答案 1 :(得分:0)
这类问题的一般适用方法是缓存中间结果,例如:如下:
#include <iostream>
#include <map>
using namespace std;
map<pair<int,int>,int> cache;
/*
The log2() and power() functions remain unchanged and so are omitted for brevity
*/
int getcount(int m,int k)
{
map<pair<int,int>, int>::const_iterator it = cache.find(make_pair(m,k));
if (it != cache.end()) {
return it->second;
}
int count = -1;
if(m==0) {
count = 1;
} else if (k<0) {
count = 0;
} else if (k==0) {
count = 1;
} else if(m>=power(2,k)) {
count = getcount(m-power(2,k),k)+getcount(m,k-1);
} else {
count = getcount(m,k-1);
}
cache[make_pair(m,k)] = count;
return count;
}
/*
The main() function remains unchanged and so is omitted for brevity
*/
原始程序(我称之为nAsSum0
)的结果是:
$ echo 1000 | time ./nAsSum0
1981471878
59.40user 0.00system 0:59.48elapsed 99%CPU (0avgtext+0avgdata 467200maxresident)k
0inputs+0outputs (1935major+0minor)pagefaults 0swaps
对于具有缓存的版本:
$ echo 1000 | time ./nAsSum
1981471878
0.01user 0.01system 0:00.09elapsed 32%CPU (0avgtext+0avgdata 466176maxresident)k
0inputs+0outputs (1873major+0minor)pagefaults 0swaps
...都在Cygwin下的Windows 7 PC上运行。因此,具有缓存的版本太快,time
无法准确测量,而原始版本需要大约1分钟才能运行。