HasanRasulov

lowest_number_erase_k_digit.cpp

Mar 10th, 2021
843
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.65 KB | None | 0 0
  1. /*
  2.  
  3. Introduction to algorithms is considered as easiest subject
  4. among the students of firstyears, so they are not focusing
  5. much on lectures. when professor realises this he becomesvery
  6. angry and plans to fail all the students of the batch. He writes a
  7. very big number on thewhiteboard and says : "This will be the
  8. minimum mark required to pass this course" . Whenstudents
  9. see this gigantic number written on the whiteboard most of
  10. them become prettysure that they are going to fail this
  11. semester. So the some of the students started trying
  12. toconvince the professor to not do so. So the professor gives
  13. them a number K and says : "Youcan erase exactly K digits of
  14. the given number". Now students want to make this number
  15. assmall as possible. So you being the second most intelligent
  16. student of the batch decide tosolve the problem. Save the
  17. other students.
  18.  
  19. */
  20.  
  21. #include <iostream>
  22. #include <string>
  23. #include <algorithm>
  24. std::string lowest_number(std::string str, int k)
  25. {
  26.     std::string res = "";
  27.     if (k == 0)
  28.     {
  29.         res.append(str);
  30.         return res;
  31.     }
  32.     if (str.length() <= k)
  33.         return res;
  34.     int min = 0;
  35.     for (int i = 1; i <= k; i++)
  36.         if (str[i] < str[min])
  37.             min = i;
  38.     res += str[min];
  39.  
  40.     return res + lowest_number(str.substr(min + 1), k - min);
  41. }
  42.  
  43. int main()
  44. {
  45.     std::string str = "412199", res = "";
  46.     int k = 2;
  47.     res = lowest_number(str, k);
  48.     size_t pos = 0;
  49.     for (size_t i = 0; i < res.length(); i++)
  50.     {
  51.         if (res[i] == '0')
  52.             pos++;
  53.         else
  54.             break;
  55.     }
  56.     res.erase(0, pos);
  57.     std::cout << res;
  58.     return 0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment