Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2017
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.40 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. int main()
  6. {
  7. long tests;
  8. cin >> tests;
  9. long count = 0;
  10.  
  11. long* sol = new long[tests];
  12.  
  13. while (count < tests) {
  14. // load array
  15. long n;
  16. cin >> n;
  17. long* a = new long[n];
  18. for (long i = 0; i < n; i++) {
  19. cin >> a[i];
  20. }
  21.  
  22. long last = a[0];
  23. long maxInSubsequence = 0;
  24. long lastIndex = 0;
  25. // longest subsequence
  26. long* T = new long[n]; // stores indexes of elements from a[]; the index of the smallest last element of some length
  27. T[0] = 0;
  28. long temp = 1;
  29.  
  30. while (temp < n) {
  31. long jump = 0;
  32. if (a[temp] > last) {
  33. //cout << "ostace na kraju: " << a[temp] << endl;
  34. last = a[temp];
  35. lastIndex = temp + 1;
  36. temp++;
  37. } else {
  38. long i = lastIndex + 1;
  39. long length = 0;
  40. T[jump] = lastIndex;
  41.  
  42. while (i < n && a[i] < last) {
  43. //cout << "processing " << a[i] << endl;
  44. if (a[i] < a[T[0 + jump]]) { //a[i] is smaller than the smallest element in the smallest subsequence
  45. T[0 + jump] = i;
  46. } else if (a[i] > a[T[length + jump]]) { //a[i] is bigger than the last element in the largest subsequence,
  47. length++; //so make a bigger subsequence with a[i] on head
  48. T[length + jump] = i;
  49. //cout << "adding: " << a[i] << endl;
  50. //cout << "length " << length << endl;
  51. } else { // a[i] is somewhere in between, binary search for the ceiling for a[i]
  52. long start = 0;
  53. long end = length;
  54. long upperMiddle = length;
  55. long middle;
  56. long ceiling;
  57. bool found = false;
  58. while (start <= end && !found) {
  59. middle = (start + end) / 2;
  60. if (middle < upperMiddle && a[T[middle + jump]] <= a[i] && a[T[middle + 1 + jump]] >= a[i]) { // comparing values from a[] with indexes from T
  61. ceiling = middle + 1;// the ceiling = the smallest value bigger than a[i]
  62. found = true;
  63. } else if (a[i] > a[T[middle + jump]]){ // if it's bigger go right, search (middle + 1, end)
  64. start = middle + 1;
  65. } else { // else if it's smaller go left, search (start, middle - 1)
  66. end = middle - 1;
  67. }
  68. }
  69. T[ceiling + jump] = i;//replace the ceiling with i
  70. }
  71. i++;
  72. }
  73.  
  74. jump += length + 1;
  75. temp = i;
  76.  
  77. if (maxInSubsequence < length + 1) maxInSubsequence = length + 1;
  78. }
  79. }
  80. sol[count] = maxInSubsequence;
  81. cout << maxInSubsequence << endl;
  82. count++;
  83. }
  84.  
  85. for (int i = 0; i < count; i++) {
  86. if (i < count - 1) cout << sol[i] << endl;
  87. else cout << sol[i];
  88. }
  89. return 0;
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement