Codeforces Round #725 (Div. 3)C. Number of Pairs

给一组数和l还有r, 求这组数中任意两个数的和在[L,R]中.

先排序, 然后求[0,R], 然后再求[0,L-1], 两个相减即可.

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0),cout.tie(0);
    int t;
    cin >> t;
    while (t --)
    {
        int n,l,r;
        cin >> n >> l >> r;
        vector<int> v; 
        int k = n;
        while (k--)
        {
            int vv;
            cin >> vv;
            v.push_back(vv);
        }
        int res = 0;
        sort(v.begin(), v.end());
        auto count = [&](int r) -> long long{
            long long res = 0;
            int i = 0, j = n - 1;
            while(i < j) {
                while(i < j && v[i] + v[j] > r)
                {
                    j--;
                }
                res += (j - i);
                i++;
            }
            return res;
        };
        cout << count(r) - count(l - 1) << endl;
    }
    return 0;
}