zoukankan      html  css  js  c++  java
  • P1102 AB 数对

    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");
    }
    
  • 相关阅读:
    学习Java书籍推荐和面试网站推荐
    Java 多线程学习扩展
    Java Excel 导入导出(二)
    Java Excel 导入导出(一)
    Matplotlib库(二)
    Matplotlib库(一)
    【转】MATLAB导出精美的论文插图
    图像的手绘效果
    Numpy库的使用(二)
    Numpy库的使用(一)
  • 原文地址:https://www.cnblogs.com/fxh0707/p/13616200.html
Copyright © 2011-2022 走看看