minke #4835(2007/12/15 18:12 GMT) [ C++ ] Rating5/5=1.00
$ g++ -O3 maho.cpp && time ./a.out 3245664 real 0m26.930s user 0m22.310s sys 0m4.560s 最初に和が (総和/n) となるn個の値の組を ビット列として全パターン生成してしまいます。 そうしておいて、ビットパターンの中から排他的なものを選んでいくアルゴリズム。 それなりに速いかと。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
#include <iostream> #include <vector> typedef unsigned int bit_t; std::vector<bit_t> bits; int n, n2, cnt = 0; void comb(int a, int k, int s, bit_t b) { if (k < n-1) for (int i = a; i < n2; ++i) comb(i+1, k+1, s-i, b | 1 << (i-1)); else if (a <= s && s <= n2) bits.push_back(b | 1 << (s-1)); } void calc(int s, int k, bit_t b) { if (k == n) { ++cnt; return; } for (int i = s; i < (int)bits.size(); ++i) if (!(b & bits[i])) calc(i+1, k+1, b | bits[i]); } int main() { n = 5; n2 = n * n; int m = n * (n2+1) / 2; comb(1, 0, m, 0); calc(0, 0, 0); std::cout << cnt << std::endl; }
Rating5/5=1.00-0+
3 replies [ reply ]
minke
#4835()
[
C++
]
Rating5/5=1.00
Rating5/5=1.00-0+
3 replies [ reply ]