【问题描述】
小明被绑架到X星球的巫师W那里。
其时,W正在玩弄两组数据 (2 3 5 8) 和 (1 4 6 7)
他命令小明从一组数据中分别取数与另一组中的数配对,共配成4对(组中的每个数必被用到)。
小明的配法是:{(8,7),(5,6),(3,4),(2,1)}
巫师凝视片刻,突然说这个配法太棒了!
因为:
每个配对中的数字组成两位数,求平方和,无论正倒,居然相等:
872 + 562 + 342 + 212 = 12302
782 + 652 + 432 + 122 = 12302
小明想了想说:“这有什么奇怪呢,我们地球人都知道,随便配配也可以啊!”
{(8,6),(5,4),(3,1),(2,7)}
862 + 542 + 312 + 272 = 12002
682 + 452 + 132 + 722 = 12002
巫师顿时凌乱了。。。。。
请你计算一下,包括上边给出的两种配法,巫师的两组数据一共有多少种配对方案具有该特征。
配对方案计数时,不考虑配对的出现次序。
就是说:
{(8,7),(5,6),(3,4),(2,1)}
与
{(5,6),(8,7),(3,4),(2,1)}
是同一种方案。
【答案提交】
注意:需要提交的是一个整数,不要填写任何多余内容(比如,解释说明文字等)
答案:24
法一:
代码如下:
#include <iostream>
using namespace std;
const int N = 6;int a[] = {2, 3, 5, 8};int b[] = {1, 4, 6, 7};
bool vis[15];
int c[N];
long long sum_a;
long long sum_b;
int ans;void dfs(int u) {if (u == 4) {for (int i = 0; i < 4; i++) {sum_a += (a[i] * 10 + c[i]) * (a[i] * 10 + c[i]);sum_b += (c[i] * 10 + a[i]) * (c[i] * 10 + a[i]);}if (sum_a == sum_b) {ans++;return ;}}for (int i = 0; i < 4; i++) {if (!vis[b[i]]) {vis[b[i]] = true;c[u] = b[i];dfs(u + 1);vis[b[i]] = false;}}
}int main() {dfs(0);cout << ans << endl;return 0;
}
法二:
代码如下:
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;int a[] = {2, 3, 5, 8};int b[] = {1, 4, 6, 7};
int ans;bool check() {LL left = 0;LL right = 0;for (int i = 0; i < 4; i++) {left += (a[i] * 10 + b[i]);right += (b[i] * 10 + a[i]);}if (left == right)return true;return false;
}int main() {do {if (check())ans++;} while (next_permutation(a, a + 4));cout << ans << endl;return 0;
}