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

POJ-2785 4 Values whose Sum is 0(折半枚举 sort + 二分)

2015-11-10 18:41 447 查看
  题目链接:http://poj.org/problem?id=2785

  题意是给你4个数列.要从每个数列中各取一个数,使得四个数的sum为0,求出这样的组合的情况个数.

其中一个数列有多个相同的数字时,把他们看作不同的数字.

  做法是把前两个数列和的值存在一个数组(A)中 , 后两个数列的和存在另一个数组(B)中 , 数组都为n^2 . 然后将B数组sort一下 , 将A数组遍历 , 二分查找一下B数组中与A数组元素和为0的个数 . 有个注意的点是万一A数组都是0 , 而B数组都为0的情况(还有其他情况) , 那二分只能找到一个与之符合的情况 . 所以可以再找刚好比符合数大的数 , 相减他们的位置, 然后加起来 , 就是答案.

这里可以用到两个函数lower_bound()和upper_bound() ,都用了二分查找,前面的函数是返回一个数组中大于或等于一个数的位置,后面的是返回大于这个数的位置(不懂的可以Google or baidu一下这两个函数怎么用).

代码如下:

#include <iostream>
#include <cstdio>
#include <algorithm>

using namespace std;
const int MAXN = 4010;
typedef long long LL;

LL a[MAXN] , b[MAXN] , c[MAXN] , d[MAXN];
LL num1[MAXN * MAXN] , num2[MAXN * MAXN];

int main()
{
int n;
while(~scanf("%d" , &n)) {
for(int i = 0 ; i < n ; i++) {
scanf("%lld %lld %lld %lld" , a + i , b + i , c + i , d + i);
}
int f = 0;
for(int i = 0 ; i < n ; i++) {
for(int j = 0 ; j < n ; j++) {
num1[f] = a[i] + b[j];
num2[f++] = c[i] + d[j];
}
}
LL res = 0;
int temp = 0;
sort(num2 , num2 + f);
for(int i = 0 ; i < f ; i++) {
temp = lower_bound(num2 , num2 + f , -num1[i]) - num2;
if(temp < f && num2[temp] + num1[i] == 0) {
res += upper_bound(num2 , num2 + f , -num1[i]) - num2 - temp;
}
}
cout << res << endl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: