## Algorithm

B. Permutations
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

You are given n k-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 contain k-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.

Examples
input
Copy
`6 4523727537523572353272537`
output
Copy
`2700`
input
Copy
`3 3010909012`
output
Copy
`3`
input
Copy
`7 550808366033719844911299944254350156`
output
Copy
`20522`
Note

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.

## Code Examples

### #1 Code Example with C++ Programming

```Code - C++ Programming```

``````#include <cstdio>
#include <vector>
#include <algorithm>

int main(){

int n, k; scanf("%d %d\n", &n, &k);

std::vector<int> perm(k); for(int p = 0; p < k; p++){perm[p] = p;}
std::vector<std::vector<int> > numbers(n, std::vector<int>(k, 0));
for(int p = 0; p < n; p++){
for(int q = 0; q < k; q++){char temp; scanf("%c", &temp); numbers[p][q] = temp - '0';}
scanf("\n");
}

long minDiff(1e10);

do{
long minNum(1e10), maxNum(0);

for(int p = 0; p < n; p++){
long current = 0;
for(int q = 0; q < k; q++){current = 10 * current + numbers[p][perm[q]];}
if(current < minNum){minNum = current;}
if(current > maxNum){maxNum = current;}
}

long diff = maxNum - minNum;
if(diff < minDiff){minDiff = diff;}

}while(next_permutation(perm.begin(), perm.end()));

printf("%ld\n", minDiff);

return 0;
}``````
Copy The Code &

Input

cmd
6 4
5237
2753
7523
5723
5327
2537

Output

cmd
2700