poj2785

大空间大时间的题,把4个数字分成两份,分别两两求和,得到两个长度n*n的一维数组,排序后比较进行匹配即可。

View Code
#include <iostream>
#include
<cstdio>
#include
<cstdlib>
#include
<cstring>
#include
<algorithm>
using namespace std;

#define maxn 4004

int n;
int f1[maxn * maxn];
int f2[maxn * maxn];
int a[maxn], b[maxn], c[maxn], d[maxn];

int main()
{
//freopen("t.txt", "r", stdin);
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++)
f1[i
* n + j] = a[i] + b[j];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
f2[i
* n + j] = c[i] + d[j];
sort(f1, f1
+ n * n);
sort(f2, f2
+ n * n);
int r = n * n - 1;
int ans = 0;
for (int i = 0; i < n * n; i++)
{
while (r >= 0 && f1[i] + f2[r] > 0)
r
--;
if (r < 0)
break;
int temp = r;
while (temp >= 0 && f1[i] + f2[temp] == 0)
ans
++, temp--;
}
printf(
"%d\n", ans);
return 0;
}

原文地址:https://www.cnblogs.com/rainydays/p/2046505.html