rk又是卡python的一次。菜是原罪----不会用c++
那就学习一下next_permutation
python
14/25
c++
25/25
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
void split_numbers(int n, std::vector<int>& digits) {
std::sort(digits.begin(), digits.end());
std::vector<int> sum_to_perms;
do {
int temp = 0;
for (int i = 0; i < n; ++i) {
temp = temp * 10 + digits[i];
}
sum_to_perms.push_back(temp);
} while (std::next_permutation(digits.begin(), digits.end()));
int m = sum_to_perms.size();
long long ss = 0;
for (auto& num : sum_to_perms) {
ss += num * num;
}
long long target = ss / 2;
for (int i = 0; i < (1 << m); ++i) {
long long sum_squares = 0;
int count = 0;
std::vector<int> ans;
for (int j = 0; j < m; ++j) {
if (i & (1 << j)) {
ans.push_back(sum_to_perms[j]);
sum_squares += static_cast<long long>(sum_to_perms[j]) * sum_to_perms[j];
++count;
}
}
if (sum_squares == target && count == m / 2) {
for (int num : ans) {
std::cout << num << std::endl;
}
return;
}
}
}
int main() {
int n;
std::cin >> n;
std::vector<int> digits(n);
for (int i = 0; i < n; ++i) {
std::cin >> digits[i];
}
split_numbers(n, digits);
return 0;
}
import itertools
def split_numbers(n, nums):
permutations = itertools.permutations(nums)
nums = []
for perm in permutations:
tep = 0
for c in perm:
tep = tep * 10 + c
nums.append(tep)
m = len(nums)
ss = 0
for c in nums:
ss += c * c
target = ss / 2
for i in range (1 << m):
a = 0
ans = []
b = 0
for j in range(m):
if i >> j & 1:
a += 1
ans.append(nums[j])
b += nums[j] ** 2
if b == target and a == m / 2:
for c in ans:
print(c)
return
if a > m / 2 or a > target:
break
n = int(input())
nums = list(map(int, input().split()))
split_numbers(n, nums)
pokemonsay -f $HOME/wz/walle2/pokemonsay/cows/Pikachu.cow “皮卡丘,我选择你!”