Beautiful Now(HDU6351)

Problem Description

Anton has a positive integer n, however, it quite looks like a mess, so he wants to make it beautiful after k swaps of digits.
Let the decimal representation of n as (x1x2⋯xm)10 satisfying that 1≤x1≤9, 0≤xi≤9 (2≤i≤m), which means n=∑mi=1xi10m−i. In each swap, Anton can select two digits xi and xj (1≤i≤j≤m) and then swap them if the integer after this swap has no leading zero.
Could you please tell him the minimum integer and the maximum integer he can obtain after k swaps?

Input

The first line contains one integer T, indicating the number of test cases.
Each of the following T lines describes a test case and contains two space-separated integers n and k.
1≤T≤100, 1≤n,k≤109.

Output

For each test case, print in one line the minimum integer and the maximum integer which are separated by one space.

Sample Input

 

5 12 1 213 2 998244353 1 998244353 2 998244353 3

Sample Output

 

12 21 123 321 298944353 998544323 238944359 998544332 233944859 998544332

题目意思为给一个九位数,让我们可以对数的任意两位进行交换k次以内,问交换之后能得到的最大值和最小值,这个题因为只有九位数,所以我们可以枚举一下全排列,但是我们全排列的是下标,不能是每一位的数,因为数有可能是相同的,而下标是唯一的,这样我们就可以找到,每个位置所处的循环节的长度,一个循环节需要的交换数量就是循环节长度减一。然后我们算一下需要的次数,与k比较就可以了,然后求一个最大值,最小值。

AC代码:

#include<stdio.h>
#include<iostream>
#include<string.h>
#include<algorithm>
#define IOS ios::sync_with_stdio(false)
#define mem(a, b) memset(a, b, sizeof(a))
using namespace std;
typedef long long LL;
int num[10], pos[10], vis[10], k;
int check(int len)
{
    mem(vis, 0);
    int cnt = 0;
    for(int i = 0; i < len; i++)
    {
        if(vis[i]) continue;
        int tmp = 0;
        while(!vis[i])
        {
            tmp++;
            vis[i] = 1;
            i = pos[i];
        }
        cnt += tmp-1;
        if(cnt > k) return 0;
    }
    return cnt;
}
int main()
{
    int T;
    IOS;
    cin >> T;
    while(T--)
    {
        string s;
        cin >> s >> k;
        int len = s.length();
        LL sum = 0;
        for(int i = 0; i < len; i++)
        {
            num[i] = s[i]-'0';
            pos[i] = i;
            sum = sum*10+(s[i]-'0');
        }
        LL ans1 = sum, ans2 = sum;
        do
        {
            if(num[pos[0]] != 0 && check(len))
            {
                LL tmp = 0;
                for(int i = 0; i < len; i++)
                {
                    tmp = tmp*10+num[pos[i]];
                }
                if(tmp < ans1)
                {
                    ans1 = tmp;
                }
                if(tmp > ans2)
                {
                    ans2 = tmp;
                }
            }
        }
        while(next_permutation(pos, pos+len));
        cout << ans1 << " " << ans2 << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/MALONG11124/article/details/81474861