Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- int main()
- {
- int tests; // number of test cases
- cin >> tests;
- int count = 0; // counter for test cases
- long* sol = new long[tests]; // array with solutions
- while (count < tests) {
- // load array
- long n;
- cin >> n; // size of the array
- if (n == 1) {
- sol[count] = 0;
- long k;
- cin >> k;
- //cout << count << " " << sol [count] << endl;
- count++;
- } else {
- long* a = new long[n];
- long last = -1; // last in the remaining sequence
- 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 = 0;
- cin >> a[0];
- 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;
- cin >> a[i];
- 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++;
- if (i < n)
- cin >> a[i];
- }
- jump += length + 1;
- if (maxInSubsequence < length + 1) maxInSubsequence = length + 1;
- temp = i + 1;
- }
- if (temp < n)
- cin >> a[temp];
- }
- /*for (int i = 0; i < n; i++) {
- cout << a[i] << endl;
- }*/
- sol[count] = maxInSubsequence;
- //cout << count << " " << sol [count] << endl;
- count++;
- }
- }
- for (int i = 0; i < count; i++) {
- cout << sol[i] << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement