Advertisement
skb50bd

Longest Increasing Subsequence

Oct 29th, 2016
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.63 KB | None | 0 0
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <string>
  4. #include <sstream>
  5. #define SIZE 100
  6. #define TAB 3
  7.  
  8. using namespace std;
  9.  
  10.  
  11. void LIS (int A[], int C[], int N) {
  12.     C[0] = 1;
  13.     int max;
  14.     for (int i = 1; i < N; i++) {
  15.         max = 0;
  16.         for (int j = i - 1; j >= 0; j--)
  17.             if (C[j] > max && A[j] < A[i])
  18.                 max = C[j];
  19.         C[i] = 1 + max;
  20.     }
  21. }
  22.  
  23.  
  24. int findLIS (int A[], int B[], int C[], int N) {
  25.     int max = 0;
  26.     int pos = 0;
  27.     for (int i = N - 1; i >= 0; i--)
  28.         if (C[i] > max) {
  29.             max = C[i];
  30.             pos = i;
  31.         }
  32.     int n = max;
  33.     for (int i = pos; i >= 0; i--)
  34.         if (C[i] == n)
  35.             B[--n] = A[i];
  36.  
  37.     return max;
  38. }
  39.  
  40.  
  41. void printSequence (int B[], int n) {
  42.     for (int i = 0; i < n; i++)
  43.         cout << B[i] << " ";
  44.     cout << endl;
  45. }
  46.  
  47.  
  48. void printArrays (int A[], int C[], int N) {
  49.     cout << "A: ";
  50.     for (int i = 0; i < N; i++)
  51.         cout << setw(TAB) << A[i];
  52.     cout << endl;
  53.     cout << "C: ";
  54.     for (int i = 0; i < N; i++)
  55.         cout << setw(TAB) << C[i];
  56.     cout << endl;
  57. }
  58.  
  59.  
  60. int main () {
  61.     string line;
  62.     cout << "Enter the Array: ";
  63.     getline(cin, line);
  64.     istringstream iss(line);
  65.  
  66.     int N, n;
  67.     int A[SIZE];
  68.     int B[SIZE];
  69.     int C[SIZE];
  70.  
  71.     for (N = 0; iss >> line; N++)
  72.         stringstream(line) >> A[N];
  73.  
  74.     LIS (A, C, N);
  75.     n = findLIS(A, B, C, N);
  76.     cout << "Length of Longest Increasing Subsequence: " << n << endl;
  77.     cout << "Longest Increasing Subsequence: ";
  78.     printSequence(B, n);
  79.     printArrays(A, C, N);
  80.  
  81.     return 0;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement