fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. using namespace std;
  5.  
  6. string findLDS(const string& sequence) {
  7. int n = sequence.size();
  8.  
  9. // dp[i] 表示以 sequence[i] 结尾的最大递减子序列的长度
  10. vector<int> dp(n, 1);
  11.  
  12. // 记录最大递减子序列的末尾位置
  13. vector<int> endPos(n, -1);
  14.  
  15. for (int i = 1; i < n; ++i) {
  16. for (int j = 0; j < i; ++j) {
  17. if (sequence[j] > sequence[i] && dp[j] + 1 > dp[i]) {
  18. //sequence[j] > sequence[i] 兩個輸入數列前後數字比較
  19. //dp[j] + 1 > dp[i] 是要找j 位置結尾的遞減數列加上當前位置的元素後
  20. //是否得到比當前以 i 位置結尾的數列長度更長
  21. dp[i] = dp[j] + 1;
  22. endPos[i] = j;
  23. //dp[i] 表示以 sequence[i] 結尾的最大遞減子序列的長度
  24. //endPos[i] 則用於記錄這個數列的前一個元素的位置
  25. }
  26. }
  27. }
  28.  
  29. // 找到最大递减子序列的末尾位置
  30. int maxLen = 0, maxEndPos = 0;
  31. for (int i = 0; i < n; ++i) {
  32. if (dp[i] > maxLen) {
  33. maxLen = dp[i];
  34. maxEndPos = i;
  35. }
  36. }
  37.  
  38. // 构造最大递减子序列
  39. string result;
  40. while (maxEndPos != -1) {
  41. result += sequence[maxEndPos];
  42. maxEndPos = endPos[maxEndPos];
  43. }
  44.  
  45. reverse(result.begin(), result.end());
  46. return result;
  47. }
  48.  
  49. int main() {
  50. string sequence;
  51. bool outend = false;
  52. while (cin >> sequence) {
  53. string LDS = findLDS(sequence);
  54. if(!outend){
  55. cout << LDS;
  56. outend = true;
  57. }else{
  58. cout << endl << LDS;
  59. }
  60. }
  61. return 0;
  62. }
  63.  
Success #stdin #stdout 0.01s 5280KB
stdin
5687643821
456879421
5932196999954321
stdout
8764321
87421
9654321