1462E1 - Close Tuples

See post for E2, this is just a special case of it.

Time complexity: $O(n \log{n})$

Memory complexity: $O(n)$

Click to show code.


using namespace std;
using ll = long long;
using ii = pair<int, int>;
using vi = vector<int>;
template <typename InputIterator,
          typename T = typename iterator_traits<InputIterator>::value_type>
void read_n(InputIterator it, int n)
{
    copy_n(istream_iterator<T>(cin), n, it);
}
ll C2(ll n)
{
    if (n < 2)
        return 0;
    return (n * (n - 1)) / 2;
}
int main(void)
{
    ios::sync_with_stdio(false), cin.tie(NULL);
    int t;
    cin >> t;
    while (t--)
    {
        int n;
        cin >> n;
        vi a(n);
        read_n(begin(a), n);
        sort(begin(a), end(a));
        ll ans = 0;
        for (int i = 0; i < n; ++i)
        {
            int j = distance(begin(a), lower_bound(begin(a), end(a), a[i] - 2));
            ans += C2(i - j);
        }
        cout << ans << endl;
    }
    return 0;
}