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

时间:2019-08-13
本文章向大家介绍UVA - 1152 --- 4 Values whose Sum is 0(二分),主要包括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;
    }

}

原文地址:https://www.cnblogs.com/KeepZ/p/11349202.html