您的位置:首页 > 产品设计 > UI/UE

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

2016-05-19 14:58 489 查看
题意:

给你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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: