解題思路
讀入三個固定數字放入 p2、p5、p8,其餘六個數字由小到大列出。若固定數字不在1..9或有重複,直接無解。
依字典序枚舉剩餘六數的排列,按位置 p1,p3,p4,p6,p7,p9 填入,再比較三邊的四數和是否相等。
這些空位的填入順序正好是整個九位數的比較順序,固定位置不影響大小比較,因此第一個合法排列就是最小答案。若枚舉完沒有合法者輸出0。
至多6!排列,每次O(9),O(1)固定空間。 Python一次讀入另佔O(輸入文字長度)空間。
Step-by-step animation
示例:p2=4、p5=3、p8=6。
步驟 1 / 3
固定436
p2=4、p5=3、p8=6。
_
4
_
_
3
_
_
6
_
- 剩餘
- 1,2,5,7,8,9
#include <bits/stdc++.h>
using namespace std;
int main() {
string s, t;
while (cin >> t)
s += t;
if (s.size() != 3) {
cout << 0 << '\n';
return 0;
}
vector<int> p(9), a;
set<int> used;
for (int i = 0; i < 3; i++) {
int x = s[i] - '0';
if (x < 1 || x > 9 || !used.insert(x).second) {
cout << 0 << '\n';
return 0;
}
p[1 + 3 * i] = x;
}
for (int x = 1; x <= 9; x++)
if (!used.count(x))
a.push_back(x);
int at[] = {0, 2, 3, 5, 6, 8};
do {
for (int i = 0; i < 6; i++)
p[at[i]] = a[i];
int x = p[0] + p[1] + p[2] + p[3], y = p[3] + p[4] + p[5] + p[6],
z = p[6] + p[7] + p[8] + p[0];
if (x == y && y == z) {
for (int v : p)
cout << v;
cout << '\n';
return 0;
}
} while (next_permutation(a.begin(), a.end()));
cout << 0 << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。