fork(1) download
  1. #include <iostream>
  2. #include <algorithm>
  3. using namespace std;
  4.  
  5. string findLDS(const string& sequence) {
  6. int n = sequence.size();
  7.  
  8. // dp[i] 表示以 sequence[i] 结尾的最大递减子序列的长度
  9. int dp[50] = {0};
  10.  
  11. // 记录最大递减子序列的末尾位置
  12. int endPos[50] = {-1};
  13.  
  14. for (int i = 1; i < n; ++i) {
  15. for (int j = 0; j < i; ++j) {
  16. if (sequence[j] >= sequence[i] && dp[j] + 1 > dp[i]) {
  17. dp[i] = dp[j] + 1;
  18. endPos[i] = j;
  19. }
  20. }
  21. }
  22. cout << dp << endl;
  23. // 找到最大递减子序列的末尾位置
  24. int maxLen = 0, maxEndPos = 0;
  25. for (int i = 0; i < n; ++i) {
  26. if (dp[i] > maxLen) {
  27. maxLen = dp[i];
  28. maxEndPos = i;
  29. }
  30. }
  31.  
  32. // 构造最大递减子序列
  33. string result;
  34. while (maxEndPos != -1) {
  35. result += sequence[maxEndPos];
  36. maxEndPos = endPos[maxEndPos];
  37. }
  38.  
  39. reverse(result.begin(), result.end());
  40. return result;
  41. }
  42.  
  43. int main() {
  44. string sequence;
  45. bool firstOutput = true; // 用于标记是否为第一次输出结果
  46. while (cin >> sequence) {
  47. string LDS = findLDS(sequence);
  48. if (!firstOutput) {
  49. cout << endl;
  50. } else {
  51. firstOutput = false;
  52. }
  53. cout << LDS;
  54. }
  55. return 0;
  56. }
  57.  
Success #stdin #stdout 0.01s 5280KB
stdin
5687643821
456879421
stdout
0x7ffcaf3ee4a0
587643210x7ffcaf3ee4a0

487421