Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- int main()
- {
- long tests;
- cin >> tests;
- long count = 0;
- long* sol = new long[tests];
- while (count < tests) {
- // load array
- long n;
- cin >> n;
- long* a = new long[n];
- for (long i = 0; i < n; i++) {
- cin >> a[i];
- }
- long last = a[0];
- long maxInSubsequence = 0;
- long lastIndex = 0;
- // longest subsequence
- long* T = new long[n]; // stores indexes of elements from a[]; the index of the smallest last element of some length
- T[0] = 0;
- long temp = 1;
- while (temp < n) {
- long jump = 0;
- if (a[temp] > last) {
- //cout << "ostace na kraju: " << a[temp] << endl;
- last = a[temp];
- lastIndex = temp + 1;
- temp++;
- } else {
- long i = lastIndex + 1;
- long length = 0;
- T[jump] = lastIndex;
- while (i < n && a[i] < last) {
- //cout << "processing " << a[i] << endl;
- if (a[i] < a[T[0 + jump]]) { //a[i] is smaller than the smallest element in the smallest subsequence
- T[0 + jump] = i;
- } else if (a[i] > a[T[length + jump]]) { //a[i] is bigger than the last element in the largest subsequence,
- length++; //so make a bigger subsequence with a[i] on head
- T[length + jump] = i;
- //cout << "adding: " << a[i] << endl;
- //cout << "length " << length << endl;
- } else { // a[i] is somewhere in between, binary search for the ceiling for a[i]
- long start = 0;
- long end = length;
- long upperMiddle = length;
- long middle;
- long ceiling;
- bool found = false;
- while (start <= end && !found) {
- middle = (start + end) / 2;
- if (middle < upperMiddle && a[T[middle + jump]] <= a[i] && a[T[middle + 1 + jump]] >= a[i]) { // comparing values from a[] with indexes from T
- ceiling = middle + 1;// the ceiling = the smallest value bigger than a[i]
- found = true;
- } else if (a[i] > a[T[middle + jump]]){ // if it's bigger go right, search (middle + 1, end)
- start = middle + 1;
- } else { // else if it's smaller go left, search (start, middle - 1)
- end = middle - 1;
- }
- }
- T[ceiling + jump] = i;//replace the ceiling with i
- }
- i++;
- }
- jump += length + 1;
- temp = i;
- if (maxInSubsequence < length + 1) maxInSubsequence = length + 1;
- }
- }
- sol[count] = maxInSubsequence;
- cout << maxInSubsequence << endl;
- count++;
- }
- for (int i = 0; i < count; i++) {
- if (i < count - 1) cout << sol[i] << endl;
- else cout << sol[i];
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement