codeforce 124B——全排列dfs——Permutations
You are given nk-digit integers. You have to rearrange the digits in the integers so that the difference between the largest and the smallest number was minimum. Digits should be rearranged by the same rule in all integers.
Input
The first line contains integers n and k — the number and digit capacity of numbers correspondingly (1 ≤ n, k ≤ 8). Next n lines containk-digit positive integers. Leading zeroes are allowed both in the initial integers and the integers resulting from the rearranging of digits.
Output
Print a single number: the minimally possible difference between the largest and the smallest number after the digits are rearranged in all integers by the same rule.
Sample Input
6 4
5237
2753
7523
5723
5327
2537
2700
3 3
010
909
012
3
7 5
50808
36603
37198
44911
29994
42543
50156
20522
Hint
In the first sample, if we rearrange the digits in numbers as (3,1,4,2), then the 2-nd and the 4-th numbers will equal 5237 and 2537 correspondingly (they will be maximum and minimum for such order of digits).
In the second sample, if we swap the second digits and the first ones, we get integers 100, 99 and 102.
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int inf = 0x3f3f3f3f; const int INF = -0x3f3f3f3f; char a[10][10]; int b[10][10]; int c[10]; int vis[10]; int ans[10]; int n, k; int anser; void dfs(int cnt) { if(cnt == k+1){ memset(c,0,sizeof(c)); for(int i = 1; i <= n; i++){ for(int j = 1; j <= k; j++){ c[i] = c[i]*10 + b[i][ans[j]]; } } sort(c + 1, c + n + 1); // printf("%d %d\n",c[n],c[1]); anser = min(anser, c[n] - c[1]); return ; } for(int i = 1; i <= k ;i++){ if(vis[i] == 0){ ans[cnt] = i; vis[i] = 1; dfs(cnt+1); vis[i] = 0; } } } int main() { while(~scanf("%d%d",&n,&k)){ anser = inf; for(int i = 1; i <= n ; i++) scanf("%s",&a[i]); for(int i = 1; i <= n; i++){ for(int j = 0;j < k; j++){ b[i][j+1] = a[i][j] - '0'; } } /* for(int i = 1; i <= n ; i++){ for(int j = 1 ; j <= k ; j++) printf("%d ", b[i][j]); puts(""); }*/ memset(vis,0,sizeof(vis)); dfs(1); printf("%d\n",anser); } return 0; }