最长递增部分

来源:互联网 发布:电子商务模拟软件 编辑:程序博客网 时间:2024/06/01 09:01
Code:
  1. #include <iostream>   
  2. #include <iomanip>   
  3. using namespace std;   
  4.   
  5. int longest_inc_sequence(int x[], int n)   
  6. {   
  7.  int *last;   
  8.  int length = 0;   
  9.  int left;   
  10.  int right;   
  11.  int mid;   
  12.  int i;   
  13.     
  14.  last = new int[n];   
  15.     
  16.  last[0] = x[0];   
  17.     
  18.  for (i = 1; i < n; ++i)   
  19.  {   
  20.   if (x[i] < last[0])   
  21.   {   
  22.    last[0] = x[i];   
  23.   }   
  24.   else if (x[i] > x[length])   
  25.   {   
  26.    ++length;   
  27.    x[length] = x[i];   
  28.   }   
  29.   else  
  30.   {   
  31.    left = 0;   
  32.    right = length;   
  33.    while (left <= right)   
  34.    {   
  35.     mid = (left + right) / 2;   
  36.     if (x[mid] > x[i])   
  37.     {   
  38.      right = mid - 1;   
  39.     }   
  40.     else  
  41.     {   
  42.      left = mid + 1;   
  43.     }   
  44.    }   
  45.    x[right] = x[i];   
  46.   }   
  47.  }   
  48.     
  49.  delete(last);    
  50.  return length + 1;   
  51. }   
  52.   
  53. int main(int argc, char *argv[])   
  54. {   
  55.   int  x[] = { 1, 3, 2, 1, 5, 7, 8, 6, 5, 9, 4, 10, 6 };   
  56.      int  n = sizeof(x)/sizeof(int);   
  57.      int  i;   
  58.   
  59.      cout << "/nLongest Increasing Sequence Program";   
  60.      cout << "/n===================================/n";   
  61.      cout << "/nGiven Array : ";   
  62.      for (i = 0; i < n; i++)   
  63.      {   
  64.           cout << setw(4) << x[i];   
  65.      }   
  66.      cout << "/n/nLength of L.I.S. is " << longest_inc_sequence(x, n) << endl;   
  67.  return 0;   
  68. }   
  69. /*  
  70. Longest Increasing Sequence Program  
  71. ===================================  
  72.  
  73. Given Array :    1   3   2   1   5   7   8   6   5   9   4  10   6  
  74.  
  75. Length of L.I.S. is 7  
  76. */  

 

原创粉丝点击