Untitled
unknown
plain_text
2 years ago
1.5 kB
11
Indexable
#include <iostream>
using namespace std;
int a[7], n, m, length, result;
int b[7];
bool foundBest;
char cur[100];
int convertToNumber() {
int num = a[0];
for(int i = 1; i < length; i++) {
num = num * 10 + a[i];
}
return num;
}
void swap(int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
void backtrack(int remain) {
if (foundBest) return;
if (remain == 0) {
int t = convertToNumber();
if (t > result) result = t;
return;
}
bool isDecrease = true;
for(int i = 1; i < length && isDecrease; ++i) {
if (a[i] > a[i - 1]) isDecrease = false;
}
if (isDecrease) {
bool hasSame = false;
for(int j = 0; j < length && !hasSame; ++j) {
for(int k = j + 1; k < length && !hasSame; ++k) {
if (a[j] == a[k]) hasSame = true;
}
}
if (!hasSame && remain % 2 != 0) {
int t = a[length - 2];
a[length - 2] = a[length - 1];
a[length - 1] = t;
}
result = convertToNumber();
foundBest = true;
return;
}
for(int i = 0; i < length; i++) {
for(int j = i + 1; j < length; j++) {
swap(i, j);
backtrack(remain - 1);
swap(i, j);
}
}
}
void solve(int index) {
cin>>cur;
cin>>m;
length = 0;
while(cur[length] != 0) {
a[length] = cur[length] - '0';
length++;
}
foundBest = false;
result = 0;
backtrack(m);
cout<<"Case #"<<index<<endl;
cout<<result<<endl;
}
int main() {
freopen("input.txt", "r", stdin);
int t;
cin>>t;
for(int i = 1; i <= t; i++) {
solve(i);
}
return 0;
}
Editor is loading...
Leave a Comment