题意: 给一个已经排序号的数字,从中间切一刀,成两个数,要求这两个数的差最小
思路:暴力比较差最小值
- stl中的next_permutation()函数进行排列 注意:这个函数必须从小到大才可以排序
- 把所有排序写出,从中间切,前面一个数,后面一个数,找到最小
if (a[mid])
{
int x = a[0]; int y = a[mid];
for (int i = 1; i < mid; i++)
x = x * 10 + a[i];
for (int i = mid + 1; i < n; i++)
y = y * 10 + a[i];
if (ans > abs(x - y))
ans = abs(x - y);
}
解决问题的代码:
#include <iostream> #include <math.h> #include <algorithm> #include <string.h> #include <cstdio> using namespace std; int n, a[15]; void solve() { while (a[0] == 0) next_permutation(a, a + n); int ans = 1000000; int mid = (n + 1) / 2; do { if (a[mid]) { int x = a[0]; int y = a[mid]; for (int i = 1; i < mid; i++) x = x * 10 + a[i]; for (int i = mid + 1; i < n; i++) y = y * 10 + a[i]; if (ans > abs(x - y)) ans = abs(x - y); } } while (next_permutation(a, a + n)); printf("%d ", ans); return; } int main() { int t; char c; scanf("%d", &t); getchar(); while (t--) { n = 0; memset(a, 0, sizeof(a)); while ((c = getchar()) != ' ') { if (c != ' ') a[n++] = c - '0'; } if (n == 1) printf("%d ", a[0]); if (n == 2) printf("%d ", abs(a[1] - a[0])); else solve(); } return 0; }