Description
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.
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.
题意:给你n个数,每个数k位,你可以任意变换每个数数位的位置,但是n个数变换的顺序要相同,求所有变换可能中,min(最大值-最小值);
思路:很明显就是求k个数的全排列。。。啊哈里介绍过,但是我竟然一点印象也没有,我真是厉害!!绝对厉害啊!!!唉。。
用深搜写出全排列,然后取出某个数字的某一位也是一个考点把。。
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 10;
int book[maxn],a[maxn], k, n, arr[maxn], ansl;
int pow(int n)
{
int ans = 1;
for(int i = 1; i < n; i++) //这里<n,让每个数*10的个数比i小,因为个位不*10
ans *= 10;
return ans;
}
int dfs(int s)
{
int temp = 0;
if(s == k + 1)
{
int min1 = 0x3f3f3f3f, max1 = -0x3f3f3f3f;
for(int i = 1; i <= n; i++)
{
temp = 0;
for(int j = 1; j <= k; j++)
temp += a[i]/pow(arr[j])%10 * pow(k-j+1); // 这里比较重要,
//取出每个的某一位,a【j】存的是第几位,a[i]是某个数;
min1 = min(min1,temp);
max1 = max(max1,temp);
}
ansl = min(max1-min1,ansl);
}
for(int i = 1; i <= k; i++)//这个for里面就是求解全排列。。。
{
if(!book[i])
{
arr[s] = i; //arr里面下表是 s ,这个跟深搜记录路径其实是一样的
book[i] = 1; //book 里面的下表是 i
dfs(s+1);
book[i] = 0;
}
}
return ansl;
}
int main()
{
while(~scanf("%d%d",&n, &k))
{
for(int i = 1; i <= n; i++)
scanf("%d",&a[i]);
memset(book,0,sizeof(book));
ansl = 0x3f3f3f3f;
printf("%d\n",dfs(1));
}
return 0;
}
下面是我队友比赛时候写的,感觉也很好把
#include<bits/stdc++.h>
using namespace std;
const int maxn = 0x3f3f3f3f;
int n, k, a[10], num[10], cha[10], p[9] = {0, 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000}, ans;
bool book[10];
void dfs(int d)
{
if(d == k+1)
{
int tmax = -0x3f3f3f3f, tmin = 0x3f3f3f3f;
for(int i = 1; i <= n; i++)
{
int temp = 0;
for(int j = 1; j <= k; j++)
temp += p[j] * (a[i]/p[num[j]]%10);
tmax = max(tmax, temp);
tmin = min(tmin, temp);
}
ans = min(ans, tmax-tmin);
}
for(int i = 1; i <= k; i++)
{
if(!book[i])
{
num[d] = i;
book[i] = 1;
dfs(d+1);
book[i] = 0;
}
}
}
int main(void)
{
while(cin >> n >> k)
{
memset(book, 0, sizeof(book));
for(int i = 1; i <= n; i++) scanf("%d", &a[i]);
ans = 0x3f3f3f3f;
dfs(1);
printf("%d\n", ans);
}
return 0;
}