C++,codeforces,2051D

// URL: https://codeforces.com/gym/2051/problem/D
#include <iostream>
#include <vector>
#include <algorithm>
void solve(){
    long long ans = 0;
    int n;long long x,y;std::cin>>n>>x>>y;
    // x <= sum - (i+j) <=y
    // sum - y <= (i+j) <= sum - x
    // 1<= i < j <= n 
    long long left = -y;
    long long right = -x;
    std::vector<long long> a(n);
    for(int i = 0;i<n;++i){
        std::cin>>a[i];
        left+=a[i];
        right+=a[i];
    }
    std::sort(a.begin(),a.end());
    int minI = 1,maxI = n-1;//n>=3, so minI and maxI are valid
    for(int index = 0;index<= n-2;++index){
        if(a[index]+a[index+1]>right){
            break;
        }
        if(minI >= (index+2)){//minI should >= index+1
            while(minI >= (index+2) && a[index]+a[minI-1]>=left){
                minI--;
            }
        }else if(minI==index||minI==(index+1)){
            minI = index+1;
            while(minI<maxI && a[index]+a[minI]<left){
                minI++;
            }
        }
        while(maxI >= (minI+1) && a[index]+a[maxI]>right){//maxI >= minI
            maxI--;
        }
        if(minI==maxI){
            if(a[index]+a[minI]>=left && a[index]+a[minI]<=right){
                ans++;
            }
            continue;
        }
        if(maxI<=index){
            continue;
        }
        ans+=(maxI-minI)+1;
    }
    std::cout<<ans<<std::endl;
}
int main(){
    int t;std::cin>>t; 
    while(t--){
        solve();
    }
    return 0;
}
posted @ 2025-03-07 20:24  Kazuma_124  阅读(17)  评论(0)    收藏  举报