AcWing 1945. Comparison of two writing methods for cow baseball (two pointers or two points)

AcWing 1945. Comparison of Two Ways of Writing Cow Baseball (Double Pointer or Two Points) Original title link

Simple

author:

Knight02

, 2022-01-19 10:56:22 , read 15


QQ picture 20220119105444.png

double pointer

#include 
#include 
#include 
using namespace std;

const int N = 1010;
int a[N];
int main()
{
    int n;
    cin >> n;

    for(int i = 1; i <= n; i ++) scanf("%d", &a[i]);
    sort(a+1, a+n+1);

    int res = 0;
    for(int i = 1; i <= n-2; i ++)
    {
        for(int j = i+1; j <= n-1; j ++)
        {
            int d = a[j]-a[i];
            int l = j+1, r = j+1;

            while(l <= n && a[l] < a[j]+d) l ++;
            while(r <= n && a[r] <= a[j]+2*d) r ++;
            res += r-l;
        }
    }
    cout << res;
    return 0;
}

two points

#include 
#include 
#include 
using namespace std;

const int N = 1010;
int a[N];
int main()
{
    int n;
    cin >> n;

    for(int i = 1; i <= n; i ++) scanf("%d", &a[i]);
    sort(a+1, a+n+1);

    int ll,rr;
    int res = 0;
    for(int i = 1; i <= n-2; i ++)
    {
        for(int j = i+1; j <= n-1; j ++)
        {
            int d = a[j]-a[i];
            int l = j+1, r = n;

            while(l >1;
                if(a[mid]a[j]+2*d) continue;
            rr = l;

            l = j+1, r = r;
            while(l >1;
                if(a[mid]>=a[j]+d) r=mid;
                else l = mid+1;
            }
            if(a[l]<a[j]+d) continue;
            ll = l;
            res += rr+1-ll;
            //cout << a[i] << " " << a[j] << " " << a[ll]<<"~"<<a[rr]<<endl;
        }
    }
    cout << res;
    return 0;
}

发现对二分的应用还不够熟练,
在求小于某个极大值的右边界以及大于某个极小值的左边界的时候总是把握不好区间的选取

.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *