ในปัญหานี้ มีการกำหนดสตริงจำนวนเต็มบวกหนึ่งสตริง เราต้องหาการเรียงสับเปลี่ยนที่มีค่าสูงสุดโดยการสลับ k ของหลักไปยังตำแหน่งต่างๆ
เราจะแก้ปัญหานี้โดยเลือกตัวเลขและสลับกับตัวเลขที่ตามมาทีละตัวเพื่อหาจำนวนสูงสุด เราทำซ้ำขั้นตอน k ครั้ง กลยุทธ์การย้อนรอยได้ผลที่นี่ เพราะเมื่อเราพบตัวเลขที่ไม่มากกว่าค่าก่อนหน้า เราจะย้อนรอยกลับไปเป็นค่าเดิมแล้วตรวจสอบอีกครั้ง
อินพุตและเอาต์พุต
Input: A number of multiple digits. The input is: 129814999 Output: The maximum value from these digits by swapping them. The output is: 999984211
อัลกอริทึม
maxNum(number, swaps, maxNumber)
อินพุต - ตัวเลขที่เป็นสตริง จำนวนการสลับ และสตริง maxNumber
ผลลัพธ์ − อัปเดต maxNumber เพื่อรับค่าที่มากที่สุด
Begin if swaps = 0, then return n := number of digits in the number for i := 0 to n-2, do for j := i+1 to n-1, do if number[i] < number[j], then exchange number[i] and number[j] if number is greater than maxNumber, then maxNumber := number maxNum(number, swaps-1, maxNumber) exchange number[i] and number[j] again for backtrack done done End
ตัวอย่าง
#include <iostream>
using namespace std;
void maxNum(string str, int swaps, string &max) {
if(swaps == 0) //when no swaps are left
return;
int n = str.length();
for (int i = 0; i < n - 1; i++) { //for every digits og given number
for (int j = i + 1; j < n; j++) {
if (str[i] < str[j]) { //when ith number smaller than jth number
swap(str[i], str[j]);
if (str.compare(max) > 0) //when current number is greater, make it maximum
max = str;
maxNum(str, swaps - 1, max); //go for next swaps
swap(str[i], str[j]); //when it fails, reverse the swapping
}
}
}
}
int main() {
string str = "129814999";
int swapNumber = 4;
string max = str;
maxNum(str, swapNumber, max);
cout <<"The given number is: " <<str << endl;
cout <<"The maximum number is: "<< max << endl;
} ผลลัพธ์
The given number is: 129814999 The maximum number is: 999984211