Advertisement
Araf_12

Longest_Increasing_Subsequence (LIS)

Apr 30th, 2025
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.65 KB | Source Code | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4.  
  5. using namespace std;
  6.  
  7. #define MAX_N 20
  8. #define EMPTY_VALUE -1
  9.  
  10. int mem[MAX_N];
  11. int next_index[MAX_N];
  12.  
  13. int f(int i, vector<int> &A) {
  14.     if (mem[i] != EMPTY_VALUE) {
  15.         return mem[i];
  16.     }
  17.    
  18.     int ans = 0;
  19.     for (int j = i + 1; j < A.size(); j++) {
  20.         if (A[j] > A[i]) {
  21.             int subResult = f(j, A);
  22.             if (subResult > ans) {
  23.                 ans = subResult;
  24.                 next_index[i] = j;
  25.             }
  26.         }
  27.     }
  28.    
  29.     mem[i] = ans + 1;
  30.     return mem[i];
  31. }
  32.  
  33. vector<int> findLIS(vector<int> A) {
  34.     int ans = 0;
  35.    
  36.     for (int i = 0; i < A.size(); i++) {
  37.         mem[i] = EMPTY_VALUE;
  38.         next_index[i] = EMPTY_VALUE;
  39.     }
  40.    
  41.     int start_index = -1;
  42.    
  43.     for (int i = 0; i < A.size(); i++) {
  44.         int result = f(i, A);
  45.         if (result > ans) {
  46.             ans = result;
  47.             start_index = i;
  48.         }
  49.     }
  50.  
  51.     vector<int> lis;
  52.     while (start_index != -1) {
  53.         lis.push_back(A[start_index]);
  54.         start_index = next_index[start_index];
  55.     }
  56.     return lis;
  57. }
  58.  
  59. int main() {
  60.     vector<int> input;
  61.     int n, val;
  62.    
  63.     cout << "Enter the number of elements: ";
  64.     cin >> n;
  65.    
  66.     cout << "Enter the elements: ";
  67.     for (int i = 0; i < n; i++) {
  68.         cin >> val;
  69.         input.push_back(val);
  70.     }
  71.    
  72.     vector<int> lis = findLIS(input);
  73.    
  74.     cout << "Longest Increasing Subsequence: ";
  75.     for (int num : lis) {
  76.         cout << num << " ";
  77.     }
  78.     cout << endl;
  79.     cout << "Length of LIS: " << lis.size() << endl;
  80.    
  81.     return 0;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement