1. 程式人生 > >HDU 6351 Beautiful Now(全排列列舉)

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

題意:給定一個數,和一個最多交換次數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;
}