UVA 1152 4 Values whose Sum is 0

分析

题目不难理解,但是有一点要注意。题目的意思是在1、2、3、4每一位上的数字可以改变顺序,但是1、2、3、4位之间不能改变顺序。

首先想简单点,如果用枚举来做,n^4一定会超时的。但是如果我们换一种思路,把这四个数字分成两部分,1/2为一组,3/4为一组,然后来二分,这样一下从n^4降到n^2。

程序

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cstdio>
 4 #include <cstdlib>
 5 using namespace std;
 6 const int MAXN = 4000 + 1;
 7 int n, a[MAXN], b[MAXN], c[MAXN], d[MAXN], ab[MAXN*MAXN], Count;
 8 int main()
 9 {
10     cin >> n;
11     for (int i = 1; i <= n; i++)
12         cin >> a[i] >> b[i] >> c[i] >> d[i];
13     for (int i = 1; i <= n; i++)
14         for (int j = 1; j <= n; j++)
15             ab[++Count] = a[i] + b[j];
16     sort(ab+1, ab+(Count+1));
17     int ans = 0;
18     for (int i = 1; i <= n; i++)
19     {
20         for (int j = 1; j <= n; j++)
21         {
22             ans += upper_bound(ab+1, ab+Count+1, -c[i]-d[j])-lower_bound(ab+1, ab+Count+1, -c[i]-d[j]);
23         }
24     }
25     cout << ans << endl;
26     return 0;
27 }
原文地址:https://www.cnblogs.com/OIerPrime/p/9215744.html