题目链接:uva 1381 - Balancing the Scale
题目大意:给出16个数,要求找出满足题目中两个算式的种数,每个数字1次。
解题思路:每次枚举4个数,然后枚举出这四个数排列的全部情况,对于每个情况有一个和(题目中的算式),判断可否用剩余的12个数字组成相同大小的值,可以的话,给8个数字的情况就要+1。最后枚举8个数字和其他8个数字可行解的乘积和,即是答案的2倍。
#include <stdio.h>
#include <string.h>
#include <vector>
#include <algorithm>
using namespace std;
const int N = 1<<16;
const int M = 20;
int num[M], v[M], s[N+5];
vector<int> g[N+5];
bool init () {
memset(s, 0, sizeof(s));
for (int i = 0; i < N; i++) g[i].clear();
scanf("%d", &num[0]);
if (num[0] == 0) return false;
for (int i = 1; i < 16; i++) scanf("%d", &num[i]);
sort(num, num + 16);
return true;
}
bool judge (int k) {
int cnt = 0;
for (int i = 0; i < 16; i++) if (k & (1<<i)) {
v[cnt++] = num[i];
}
return cnt == 4;
}
int solve () {
for (int i = 0; i < N; i++) if (judge(i)) {
do {
int cur = v[0] * 4 + v[1] * 3 + v[2] * 2 + v[3];
for (int j = 0; j < g[cur].size(); j++) if ((i & g[cur][j]) == 0) {
s[i|g[cur][j]]++;
}
g[cur].push_back(i);
} while (next_permutation(v, v + 4));
}
int ans = 0;
for (int i = 0; i < N; i++) {
ans += s[i] * s[i ^ (N-1)];
}
return ans/2;
}
int main () {
int cas = 1;
while (init()) {
printf("Case %d: %d\n", cas++, solve());
}
return 0;
}