您的位置:首页 > 其它

CodeForces 124B Permutations

2015-06-18 16:01 330 查看
PermutationsTime Limit:1000MS Memory Limit:262144KB 64bit IO Format:%I64d
& %I64u
SubmitStatusPracticeCodeForces
124B

Description

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 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

Input
6 4
5237
2753
7523
5723
5327
2537


Output
2700


Input
3 3
010
909
012


Output
3

/***********************************************
 * Author: fisty
 * Created Time: 2015/6/15 21:14:23
 * File Name   : A.cpp
 *********************************************** */
#include <iostream>
#include <cstring>
#include <deque>
#include <cmath>
#include <queue>
#include <stack>
#include <list>
#include <map>
#include <set>
#include <string>
#include <vector>
#include <cstdio>
#include <bitset>
#include <algorithm>
using namespace std;
#define Debug(x) cout << #x << " " << x <<endl
#define Memset(x, a) memset(x, a, sizeof(x))
const int INF = 0x3f3f3f3f;
typedef long long LL;
typedef pair<int, int> P;
#define FOR(i, a, b) for(int i = a;i < b; i++)
#define MAX_N 10
int n, k;
int c[MAX_N];
int z[MAX_N];
char b[MAX_N][MAX_N];
int ans;
int solve(){
    FOR(i, 0, n){
        FOR(j, 0, k){
            cin >> b[i][j];
        }
    }
    for(int i = 0;i < k; i++){
        c[i] = i;
    }
    ans = INF;
    do{
//        for(int i = 0;i < k; i++){
//            cout << c[i] << " ";
//        }
//        cout << endl;
        int _max = -INF, _min = INF;
        for(int i = 0;i < n; i++){
            int a = 0;
            for(int j = 0;j < k; j++){
                a += (b[i][c[j]]-'0') * z[k-j-1];
            }
            _min = min(_min, a);
            _max = max(_max, a);
        }
        //Debug(_max);
        //Debug(_min);
        ans = min(ans, _max - _min);
    }while(next_permutation(c, c + k));
    return ans;
}
int main() {
    //freopen("in.cpp", "r", stdin);
    cin.tie(0);
    ios::sync_with_stdio(false);
    cin >> n >> k;
    z[0] = 1;
    for(int i = 1;i < k; i++){
        z[i] = z[i-1] * 10;
    }
    cout << solve() << endl;
    return 0;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: