CodeForces - 124B-Permutations(DFS)

本文探讨了一种算法问题,即如何通过重新排列一组k位数的整数中的数字,使得这些整数之间的最大值和最小值之差达到最小。文章详细介绍了输入输出格式,并提供了示例说明。该问题涉及深度优先搜索和回溯算法。

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

6 4
5237
2753
7523
5723
5327
2537

Output

2700

Input

3 3
010
909
012

Output

3

Input

7 5
50808
36603
37198
44911
29994
42543
50156

Output

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.

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>

using namespace std;
char s[100][100],str[100];
int vis[100],k,cha,b[100],n;
#define inf 99999999
void dfs(int wei)
{
	int i,j,minx=inf,maxx=-inf,num;
	if(wei==k+1){
	
		for(i=1;i<=n;i++){
			num=0;
			for(j=1;j<=k;j++){
				num=num*10+s[i][b[j]]-'0';
			}
			maxx=max(maxx,num);
			minx=min(minx,num);
		}
		cha=min(cha,maxx-minx);//return;
	}
	else{
		 for(i=1;i<=k;i++){
		   if(!vis[i]){
			  vis[i]=1;
			  b[wei]=i;
			  dfs(wei+1);
			  vis[i]=0;
		   }
	    }
	}
}
 
 
int main()
{
	int m,i,j,t,num;
	char c;
	while(scanf("%d%d",&n,&k)!=EOF)
	{
		for(i=1;i<=n;i++){
			scanf("%s",s[i]+1);
		}
		cha=inf;
		if(n==1){
			printf("0\n");continue;
		}
		memset(vis,0,sizeof(vis));
		dfs(1);
		printf("%d\n",cha);
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

black-hole6

你的鼓励将是我创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值