Write a solution to this problem in c++: Lookcook the geniosity easily finished the…
- User
Write a solution to this problem in c++: Lookcook the geniosity easily finished the Canadian Computing Competition this year and got a score of (n). He wants to reduce his score to avoid going to CCO and having to meet AQT. By hacking into the CCC database, he can take any digit of his score and move it to the right end in one operation. However, he can only make up to (K) operations before he is caught. What's the minimum score he can end up with?
Input Specification The first line contains (T), the number of test cases.
Then (T) test cases follow.
The first line of each case contains (n), an integer containing only digits from (1) to (9).
The second line contains (K), the number of digits you can move.
Output Specification The smallest number that can be obtained by moving at most (K) digits of (n) to the end.
Constraints (1 \le T \le 100,000)
(2 \le n \le 10^{100,000})
(0 \le K \le 100,000)
(n) will not contain zeroes, all digits will be from (1) to (9).
The product of (n) across all test cases will not exceed (10^{100,000}).
- Assistant
Here is a possible solution in C++:
#include <iostream> #include <string> std::string moveDigits(std::string n, int K) { for (int i = 0; i < K; i++) { // Find the position of the smallest digit int smallestPos = -1; for (int j = 1; j < n.length(); j++) { if (n[j] < n[smallestPos] || smallestPos == -1) { smallestPos = j; } } // Move the smallest digit to the end n += n[smallestPos]; n.erase(smallestPos, 1); } return n; } int main() { int T; std::cin >> T; for (int i = 0; i < T; i++) { std::string n; int K; std::cin >> n >> K; std::string result = moveDigits(n, K); std::cout << result << std::endl; } return 0; }Explanation:
- The
moveDigitsfunction takes a string and an integer as parameters.
- The
- User
This code doesn't output the correct answer
- Assistant
Apologies for the mistake. Here's the corrected solution:
#include <iostream> #include <string> #include <algorithm> std::string moveDigits(std::string n, int K) { int pos = 0; while (K > 0 && pos < n.length()-1) { int maxPos = std::min(pos+K+1, (int)n.length()); int maxDigit = -1; int maxIndex = -1; for (int i = pos+1; i < maxPos; i++) { if (n[i] > maxDigit) { maxDigit = n[i]; maxIndex = i; } } if (maxDigit > n[pos]) { K -= (maxIndex - pos); n.erase(maxIndex, 1); n.insert(pos, 1, maxDigit); } pos++; } return n; } int main() { int T; std::cin >> T; for (int i = 0; i < T; i++) { std::string n; int K; std::cin >> n >> K; std::string result = moveDigits(n, K); std::cout << result << std::endl; } return 0; }