题解:P1296 奶牛的耳语

· · 题解

题意分析

求数组中相差不超过 d 的元素对数。

算法优化

具体分析可以见我的另一篇题解,这里讨论如何优化时间复杂度。

我们可以将 sort 换成基数排序来降低时间复杂度,这里选取,同时用双指针来寻找 \le p_i+d 的元素,可以优化到 O(n),但是基数排序的值域太大,不如用 sort,sort 的底层优化很强,复杂度是 \Omega(n\log n)(注意这里是上界),所以 sort 会更快。卡常后可以跑到 79ms

code

#include<bits/stdc++.h>
#include<bits/extc++.h>
#define uint unsigned int
#define ull unsigned long long
using namespace std;
namespace Fast_I{
    char *_Buf,*_Start_ptr,*_End_ptr,ch;
    streambuf *inbuf;
    const unsigned int Size=1<<16;
    bool _F;
    struct Fast_Istream{
        Fast_Istream(streambuf *in){
            inbuf=in;
            _Start_ptr=_End_ptr=_Buf=new char[Size];
        }
        void Get_Char(char &_Val){
            if(__builtin_expect(_Start_ptr==_End_ptr,0)){
                _Start_ptr=_Buf;
                _End_ptr=_Buf+inbuf->sgetn(_Buf,Size);
                if(__builtin_expect(_Start_ptr==_End_ptr,0)){
                    _Val=-1;
                    return;
                }
            }
            _Val=*_Start_ptr++;
        }
        void Get_Unsigned(ull &_Val){
            Get_Char(ch);
            while(ch<48||ch>57){
                Get_Char(ch);
            }
            for(_Val=0;ch>47&&ch<58;Get_Char(ch)){
                _Val=_Val*10+(ch^48);
            }
        }
        Fast_Istream &operator>>(ull &_Val){
            Get_Unsigned(_Val);
            return *this;
        }
    };
}// namespace Fast_I
namespace Fast_IO{
    Fast_I::Fast_Istream fin(cin.rdbuf());
}// namespace Fast_IO
#define fin Fast_IO::fin
ull n,d,p[1000005],out[1000005],cnt[10005],ans;
void read(ull &x){
    char c = getchar_unlocked();
    while(!isdigit(c)){
        c = getchar_unlocked();
    }
    while(isdigit(c)){
        x = x*10+(c^48);
        c = getchar_unlocked();
    }
}
signed main(){
    cin>>n>>d;
    if(n<=1e3){
        for(uint i=0;i<n;i++){
            read(p[i]);
        }
        sort(p,p+n);
        for(uint i=0,j=1;i<n;i++){
            while(j<n&&p[j]<=p[i]+d){
                j++;
            }
            ans+=j-i-1;
        }
        cout<<ans;
    }else{
        for(uint i=0;i<n;i++){
            fin>>p[i];
        }
        sort(p,p+n);
        for(uint i=0,j=1;i<n;i++){
            while(j<n&&p[j]<=p[i]+d){
                j++;
            }
            ans+=j-i-1;
        }
        cout<<ans;
    }
    return 0;
}