刷题记录|POJ2785题解

Description

The SUM problem can be formulated as follows: given four lists A, B, C, D of integer values, compute how many quadruplet (a, b, c, d ) ∈ A x B x C x D are such that a + b + c + d = 0 . In the following, we assume that all lists have the same size n .

Input

The first line of the input file contains the size of the lists n (this value can be as large as 4000). We then have n lines containing four integer values (with absolute value as large as 228 ) that belong respectively to A, B, C and D .

Output

For each input file, your program has to write the number quadruplets whose sum is zero.

Sample Input

6
-45 22 42 -16
-41 -27 56 30
-36 53 -37 77
-36 30 -75 -46
26 -38 -10 62
-32 -54 -6 45

Sample Output

5

解题思路:

由于用暴力求解需要四个for循环,这样时间复杂度过高,这里可以进行优化4列分为两组,两列两列为一组,然后分别计算他们的组合,放到p,q数组中,然后通过二分在q数组中找p数组的数的相反数,由此来解决问题。

AC代码

#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 4010;
int arr[N][6];
int p[N * N];
int q[N * N];
int n;

//将四列分成两列处理
void func(int* a, int x, int y)
{
	int cnt = 0;
	for (int i = 1; i <= n; i++)
	{
		for (int j = 1; j <= n; j++)
		{
			a[++cnt] = arr[i][x] + arr[j][y];
		}
	}
}
int main()
{
	scanf("%d", &n);
	for (int i = 1; i <= n; i++)
	{
		scanf("%d%d%d%d", &arr[i][1], &arr[i][2], &arr[i][3], &arr[i][4]);
	}
	func(p, 1, 2);
	func(q, 3, 4);
	sort(q + 1, q + 1 + n * n);
	long long cnt = 0;
	for (int i = 1; i <= n * n; i++)
	{
		cnt += upper_bound(q + 1, q + 1 + n * n, -p[i]) - lower_bound(q + 1, q + 1 + n * n, -p[i]);
	}
	cout << cnt << endl;
	return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值