UVA - 1152 --- 4 Values whose Sum is 0(二分)

问题分析

首先枚举a和b, 把所有a+b记录下来放在一个有序数组,然后枚举c和d, 在有序数组中查一查-c-d共有多少个。注意这里不可以直接用二分算法的那个模板,因为那个模板只能查找是否有某个数,一旦找到便退出。利用lower_bound,upper_bound比较方便,这两个函数就是用二分实现的,二者之差就是相等的那部分。

代码

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
LL T, n;
const int maxn = 4000 + 10;
LL a[maxn], b[maxn], c[maxn], d[maxn];
LL s1[maxn*maxn];
int cnt, ans;
int main()
{
    std::ios::sync_with_stdio(false);
    //freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);
    cin >> T;
    for(LL t = 1; t <= T; t++)
    {
        cnt = 0, ans = 0;
        if(t != 1)
            cout << endl;
        cin >> n;
        for(LL i = 0; i < n; i++)
            cin >> a[i] >> b[i] >> c[i] >> d[i];
        memset(s1, 0, sizeof(s1));
        for(LL i = 0; i < n; i++)
            for(LL j = 0; j < n; j++)
            {
                s1[cnt] = a[i] + b[j];
                cnt++;
            }
        sort(s1, s1 + cnt);
        for(LL i = 0; i < n; i++)
        {
            for(LL j = 0; j < n; j++)
            {
                ans += upper_bound(s1, s1 + cnt, -(c[i] + d[j])) - lower_bound(s1, s1 + cnt, -(c[i] + d[j]));
            }
        }
        cout << ans << endl;
    }

}
posted @ 2019-08-13 23:07  DIY-Z  阅读(110)  评论(0编辑  收藏  举报