1. 程式人生 > >2018 hdu多校第五場 1002 Beautiful Now

2018 hdu多校第五場 1002 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

這道題emmm一開始想決策,後來貪心。。。絕望的很,四個小時換了四五種寫法。。。。然後告訴我是個暴力

涉及到一種比較少用的語法next_permutation

就是全排列,可以將你的陣列中的某一段元素進行全排列。

題目思路有點反向思考了,我想的是怎麼從開頭開始逐步處理,但是答案是先用next先打亂順序,然後再計算從初始數字到打亂後要幾步,然後步數符合的再暴搜最大最小值,然後加入了一些剪枝,比如步數超過9的一定是字典序,有前導零的直接跳過,可以降低一些耗時,但是感覺在資料範圍內想卡住還是能卡住的。。。。。

貼程式碼~~~

#include <bits/stdc++.h>
#define maxn 20
using namespace std;

char a[maxn];
int c[maxn],q[maxn],q1[maxn],p[maxn],k,len;
int minn,maxx;

void init() {
	memset(q,0,sizeof(q));
	memset(q1,0,sizeof(q1));
}

void updata(){
	if(c[p[1]] == 0) return ;
	for(int i = 1;i <= len;i++){
		q[i] = p[i];
	}
	int k1 = 0,s = 0;
	for(int i = 1;i <= len;i++){
		s = s * 10 + c[p[i]];
		if(q[i] != i){
			for(int j = i + 1;j <= len;j++){
				if(q[j] == i){
					swap(q[i],q[j]);
					k1++;
					if(k1 > k) return;
					break;
				}
			}
		}
	}
	if(k1 > k) return ;
	maxx = max(maxx,s);
	minn = min(minn,s);
}

int main () {
	int T;
	cin >> T;
	while(T--) {
		init();
//		getchar();
		scanf("%s %d",a + 1,&k);
		len = strlen(a + 1);
		for(int i = 1; i <= len; i++) {
			c[i] = a[i] - '0';
			q[c[i]]++;
			q1[c[i]]++;
		}
		if(k >= len - 1) {
			for(int i = 1; i <= 9; i++) {
				if(q[i]) {
					printf("%d",i);
					q[i]--;
					break;
				}
			}
			for(int i = 0; i <= 9; i++) {
				while(q[i]) {
					printf("%d",i);
					q[i]--;
				}
			}
			printf(" ");
			for(int i = 9; i >= 0; i--) {
				while(q1[i]) {
					printf("%d",i);
					q1[i]--;
				}
			}
			printf("\n");
			continue;
		}
		for(int i = 1;i <= len;i++) p[i] = i;
		minn = 2e9,maxx = -1;
		do{
			updata();
		}while(next_permutation(p + 1,p + len + 1));
		printf("%d %d\n",minn,maxx);
	}
	return 0;
}