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

Divide and conquer:4 Values whose Sum is 0(POJ 2785)

2016-02-01 13:40 525 查看
                 


                找四个数的和为0

  题目大意:给定四个集合,要你每个集合选4个数字,组成和为0

  这题是3977的简单版,只要和是0就可以了

  

#include <iostream>
#include <algorithm>
#include <functional>
#define MAX 4001

using namespace std;

typedef long long LL_INT;
static LL_INT list[4][MAX], set_sum1[MAX*MAX];

LL_INT *Binary_Lower_Bound(int &, LL_INT);
LL_INT *Binary_Upper_Bound(int &, LL_INT);
LL_INT solve(int &,int &);

int main(void)
{
int list_contian, sum_comb;
LL_INT ans;

while (~scanf("%d", &list_contian))
{
for (int i = 0; i < list_contian; i++)
scanf("%lld%lld%lld%lld", &list[0][i], &list[1][i], &list[2][i], &list[3][i]);

sum_comb = 0;
for (int i = 0; i < list_contian; i++)//把第一张和第二张表的总数枚举出来
for (int j = 0; j < list_contian; j++)
set_sum1[sum_comb++] = list[0][i] + list[1][j];

sort(set_sum1, set_sum1 + sum_comb);
ans = solve(list_contian, sum_comb);
printf("%lld\n", ans);
}
return EXIT_SUCCESS;
}

LL_INT solve(int &list_contain, int &sum_comb)
{
LL_INT tmp_sum, ans = 0;
int pos1, pos2;

for (int i = 0; i < list_contain; i++)
{
for (int j = 0; j < list_contain; j++)
{
tmp_sum = -list[2][i] - list[3][j];
pos1 = Binary_Upper_Bound(sum_comb, tmp_sum) - set_sum1;
pos2 = Binary_Lower_Bound(sum_comb, tmp_sum) - set_sum1;
ans += pos1 - pos2;
}
}
return ans;
}

LL_INT *Binary_Lower_Bound(int &sum_comb, LL_INT val)
{
int lb = 0, mid, count1 = sum_comb, count2;
while (count1 > 0)
{
count2 = count1 >> 1;
mid = lb + (count1 >> 1);
if (set_sum1[mid] < val)
{
lb = ++mid;
count1 -= count2 + 1;
}
else count1 = count2;
}
return &set_sum1[lb];
}

LL_INT *Binary_Upper_Bound(int &sum_comb, LL_INT val)
{
int lb = 0, mid, count1 = sum_comb, count2;
while (count1 > 0)
{
count2 = count1 >> 1;
mid = lb + (count1 >> 1);
if (set_sum1[mid] <= val)
{
lb = ++mid;
count1 -= count2 + 1;
}
else count1 = count2;
}
return &set_sum1[lb];
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: