不知道有啥简单方法,,,傻逼式暴力出来的。
#pragma warning(disable:4996) #include <cstdio> #include <cmath> #include <cstring> #include <algorithm> #include <iostream> #include <vector> using namespace std; int num[10], a[10], b[10], cnt1, cnt2; vector<int>x, y; bool vis[10]; void dfs(int num[], int type, int pos, int cnt, int ret) { if (pos == 0) { if (type == 1)x.push_back(ret); else y.push_back(ret); return; } for (int i = 0; i < cnt; i++) { if (vis[i])continue; if (num[i] == 0 && pos == cnt&&cnt != 1)continue; int nxt = ret + num[i] * (int)pow(10.0, (pos - 1)*1.0); vis[i] = true; dfs(num, type, pos - 1, cnt, nxt); vis[i] = false; } } int getMax(int num[], int cnt) { int ret = 0; for (int i = cnt - 1; i >= 0; i--) { ret += num[i] * (int)pow(10.0, i*1.0); } return ret; } int getMin(int num[], int cnt) { int ret = 0; if (num[0] == 0) { if (cnt == 1)return 0; else { swap(num[0], num[1]); } } for (int i = 0; i < cnt; i++) { ret += num[i] * (int)pow(10.0, (cnt - 1 - i)*1.0); } return ret; } int main() { int t; scanf("%d", &t); while (t--) { int n = 0, X; while (cin >> X) { num[n++] = X; if (cin.peek() == '\n')break; } int ans = -1; for (int i = 1; i < (1 << n) - 1; i++) { cnt1 = cnt2 = 0; int tmp = i, id = 0; while (tmp) { if (tmp & 1)a[cnt1++] = num[id]; else b[cnt2++] = num[id]; id++; tmp >>= 1; } while (id < n)b[cnt2++] = num[id++]; if (cnt1 == cnt2) { x.clear(); y.clear(); memset(vis, false, sizeof vis); dfs(a, 1, cnt1, cnt1, 0); memset(vis, false, sizeof vis); dfs(b, 2, cnt2, cnt2, 0); for (int u = 0; u < (int)x.size(); u++) { for (int v = 0; v < (int)y.size(); v++) { int tmp = abs(x[u] - y[v]); if (ans == -1)ans = tmp; else ans = min(tmp, ans); } } } else { if (cnt1 > cnt2) { int tmp = getMin(a, cnt1) - getMax(b, cnt2); if (tmp < 0)tmp = -tmp; if (ans == -1)ans = tmp; else ans = min(tmp, ans); } else { int tmp = getMin(b, cnt2) - getMax(a, cnt1); if (tmp < 0)tmp = -tmp; if (ans == -1)ans = tmp; else ans = min(tmp, ans); } } } printf("%d\n", ans); } return 0; }