poj2785 二分查找

題目大意:給定n行數(n<=4000),每行4個數。從這4列中,每列選擇一個數使其和爲0

暴力枚舉 O(n^4)會tle。
優化:枚舉第1,2列算出總和s1[],枚舉第3,4列算出總和s2[]。然後枚舉s1[],在s2[]中二分查找等於-s1[]的數即可 O(n^2log(n^2))

第一次WA:沒有認識到,s2[]數組中有相同的數,所以找到一個就++ans。
正解:在s2[]中找到第一個>key的位置pos1,再找到第一個>=key的位置pos2,則ans+=(pos1-pos2);

#include <cstdio>
#include <algorithm>

using namespace std;
const int N = 4e3+5;
const int M = 16e6+5;
int a[5][N];
int s1[M],s2[M];
int n;

int upper_find(int l, int r, int key)
{
    while(l<=r)
    {
        int mid = (l+r)>>1;
        if(s2[mid]>key) r = mid-1;
        else l = mid+1;
    }
    return r+1;
}

int lower_find(int l, int r, int key)
{
    while(l<=r)
    {
        int mid = (l+r)>>1;
        if(s2[mid]>=key) r = mid-1;
        else l = mid+1;
    }
    return r+1;
}

int main()
{
    scanf("%d", &n);
    for(int i = 1; i <= n; ++i)
        scanf("%d %d %d %d", &a[1][i], &a[2][i], &a[3][i], &a[4][i]);
    int tot = 0;
    for(int i = 1; i <= n; ++i)
        for(int j = 1; j <= n; ++j)
            s1[++tot] = a[1][i]+a[2][j];
    tot = 0;
    for(int i = 1; i <= n; ++i)
        for(int j = 1; j <= n; ++j)
            s2[++tot] = a[3][i]+a[4][j];
    int ans = 0;
    sort(s2+1, s2+tot+1);
    for(int i = 1; i <= tot; ++i)
        ans += upper_find(1, tot, -s1[i])-lower_find(1, tot, -s1[i]);
    printf("%d\n", ans);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章