P1102 A-B 数对

my solution

  • \(A-B=C\)转换成\(A=B+C\),a数组记录A的值,b数组记录B+C的值
  • 问题转化为a,b数组中相等的数的配对数
  • t为当前配对的数,l记录当前a数组中配对数的个数,r记录b数组中配对数的个数
  • 根据乘法原理,res每次加上\(l*r\)
const int N=2e5+10;
int a[N],b[N];
int n,x;

int main()
{
    cin>>n>>x;

    for(int i=0;i<n;i++) cin>>a[i];
    for(int i=0;i<n;i++) b[i]=a[i]+x;

    sort(a,a+n);
    sort(b,b+n);

    int i=0,j=0;
    LL res=0;
    while(i<n && j<n)
    {
        while(i<n && a[i] < b[j]) i++;
        while(j<n && a[i] > b[j]) j++;
        if(a[i] == b[j])
        {
            int l=0,r=0;
            int t=a[i];
            while(i<n && a[i] == t) l++,i++;
            while(j<n && b[j] == t) r++,j++;
            res+=(LL)l*r;
        }
    }

    cout<<res<<endl;

    //system("pause");
}

other solution

\(二分\)

const int N=2e5+10;
int a[N];
int n,x;

int main()
{
    cin>>n>>x;

    for(int i=0;i<n;i++) cin>>a[i];
    sort(a,a+n);

    LL res=0;
    for(int i=0;i<n;i++)
        res+=upper_bound(a,a+n,a[i]+x)-lower_bound(a,a+n,a[i]+x);

    cout<<res<<endl;

    //system("pause");
}

\(map\)

const int N=2e5+10;
int a[N];
unordered_map<int,int> mp;
int n,x;

int main()
{
    cin>>n>>x;

    for(int i=0;i<n;i++) cin>>a[i],mp[a[i]+x]++;

    LL res=0;
    for(int i=0;i<n;i++) res+=mp[a[i]];
    cout<<res<<endl;

    //system("pause");
}
posted @ 2020-09-04 21:10  Dazzling!  阅读(189)  评论(0编辑  收藏  举报