Segment Tree Code

 #include <bits/stdc++.h>

using namespace std;

#define nl "\n"

#define int long long 

#define debug cout<<"Error" << nl;

#define FAST ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);


bool cmp(const pair<int, int> &a, const pair<int, int> &b)

{

    if (a.first != b.first)

    {

        return a.first > b.first;

    }

    return a.second < b.second;

}

signed main()

{

    FAST

    int t;

    cin >> t;

    while(t--)

    {

       int n,x;

       cin >> n >> x;

       vector<int>v(n);

       for(int i=0;i<n;i++)

       {

        cin >>v[i];

       }

       int c=0;

       int a=(v[0]-x);

       int b=(v[0]+x);

       for(int i=1;i<n;i++)

       {

        int m=v[i]-x;

        int o=v[i]+x;

        if(((a>=m and a<=o) || (b>=m and b<=o))or

            ((m>=a and m<=b) || (o>=a and o<=b)))

        {

            a = max(m,a),b = min(o,b);

        }else{

            c++;

            a = m, b = o;

        }

       }

       cout << c << nl;

    }

    return 0;

}

Comments