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
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef unsigned int bit_t;

vector<bit_t> bits;
bit_t mask;
int n, n2;
long long cnt = 0LL;

void comb(int a, int k, bit_t b, int rest) {
  if (k == n-1) {
    if (rest <= n2)
      bits.push_back(b | 1 << (rest-1));
    return;
  }
  for (int i = a; i < n2; ++i)
    if (rest-i > i)
      comb(i+1, k+1, (b | 1 << (i-1)), rest-i);
}

void calc(int a, int k, bit_t b) {
  if (k == n-1) {
    if (binary_search(bits.begin()+a, bits.end(), mask & ~b))
      ++cnt;
    return;
  }
  for (int i = a; i < (int)bits.size(); ++i)
    if (!(b & bits[i]))
      calc(i+1, k+1, b | bits[i]);
}

int main(int argc, char **argv) {
  n = argc > 1 ? atoi(argv[1]) : 5;
  n2 = n * n;
  mask = (1 << n2) - 1;
  int m = n * (n2+1) / 2;

  comb(1, 0, 0, m);
  sort(bits.begin(), bits.end());
  calc(0, 0, 0);

  cout << cnt << endl;
}