例题 8-3 UVA - 1152 4 Values whose Sum is 0(和为0的4个值)(二分枚举)

来源:互联网 发布:淘宝网店申请多少钱 编辑:程序博客网 时间:2024/05/29 04:13

题意:

给你4个n 元素的集合ABCD,要求分别从中选取一个元素abcd使得a + b + c + d = 0问有多少种选法!

思路:

先把A数组和B数组所有的组合情况都记录到tmp数组,排序,然后枚举C数组和D数组,取相反数,然后二分枚举tmp数组中值,

取上界upper_bound 和取下界 lower_bound 做差即可!

#include<cstdio>#include<cstring>#include<algorithm>using namespace std;const int maxn = 5000 + 5;int a[maxn],b[maxn],c[maxn],d[maxn];int tmp[maxn*maxn];int main(){    int T,cnt2 = 0;    scanf("%d",&T);    while(T--){        int n,cnt=0;        scanf("%d",&n);        for (int i = 0; i < n; ++i){            scanf("%d%d%d%d",&a[i],&b[i],&c[i],&d[i]);        }        for (int i = 0; i < n; ++i)            for (int j = 0; j < n; ++j)                tmp[cnt++] = a[i] + b[j];        sort(tmp,tmp+cnt);        int ans = 0;        for (int i = 0; i < n; ++i){            for (int j = 0; j < n; ++j){                int k = -c[i]-d[j];                int pos1 = upper_bound(tmp,tmp+cnt,k) - tmp;                int pos2 = lower_bound(tmp,tmp+cnt,k) - tmp;                ans += pos1-pos2;            }        }        if (cnt2++)printf("\n");        printf("%d\n",ans);    }    return 0;}


0 0
原创粉丝点击