HDU 6351 Beautiful Now(全排列枚举)

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

Source

2018 Multi-University Training Contest 5

题意:给定一个数,和一个最多交换次数k,问在不超过k次操作的情况,问可以得到的最大值和最小值是多少?

思路:保存下标,全排列枚举下标。

难点:对于每次的排列,如何确定它的交换次数?看循环结的个数就行!

具体看代码:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>
#include <map>
#include <vector>
#include <set>
#include <string>
#include <math.h>
#include <stack>
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define Lson l,m,rt<<1
#define Rson m+1,r,rt<<1|1
const int maxn = 1e5+10;
const int mod=1<<30;
#define inf 0x3f3f3f3f
int c[maxn];
char s[20];
int n;
bool vis[20];
int k;
bool check()
{
    memset(vis,0,sizeof(vis));
    int tmp=0;
    for(int i=0;i<n;i++)
    {
        if(vis[i]) continue;
        int x=0;
        while(vis[i]==0)
        {
            x++;
            vis[i]=1;
            i=c[i];
        }
        tmp+=x-1;
        if(tmp>k) return 0;
    }
    return tmp<=k;
}
int main(int argc, char const *argv[])
{
    #ifndef ONLINE_JUDGE
        freopen("in.txt","r",stdin);
        freopen("out.txt","w",stdout);
    #endif
    int T;
    cin>>T;
    while(T--)
    {
       scanf("%s%d",s,&k);
        int Min=1e9+7;
        int Max=0;
        n=strlen(s);
        for(int i=0;i<n;i++)
        {
            c[i]=i;
        }
        do
        {
            if(s[c[0]]!='0'&&check())
            {
                ll ans=0;
                for(int i=0;i<n;i++)
                {
                    ans=ans*10+(s[c[i]]-'0');
                }
                if(ans>Max)
                {
                    Max=ans;
                }
                if(ans<Min)
                {
                   Min=ans;
                }
            }
        }while(next_permutation(c,c+n));
        cout<<Min<<" "<<Max<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40774175/article/details/81460942