[中途相遇法] UVa1152 4 Values whose Sum is 0 和为0的四个数 (卡常)

题目

给定4个n(1<=n<=4000)元素组合A,B,C,D,要求分别从中选取一个元素a,b,c,d,使得a+b+c+d=0。问:有多少种解法。
例如: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
结果:5
选法:
(-45,-27,42,30),(26,30,-10,-46)
(-32,22,56,-46),(-32,30,-75,77),(-32,-54,56,30)

代码

#include<cstdio>
#include<algorithm>
using namespace std;

const int maxn = 4000 + 5;
int n, c, A[maxn], B[maxn], C[maxn], D[maxn], sums[maxn*maxn];

int main() {
  int T;
  scanf("%d", &T);
  while(T--) {
    scanf("%d", &n);
    for(int i = 0; i < n; i++)
      scanf("%d%d%d%d", &A[i], &B[i], &C[i], &D[i]);
    c = 0;
    for(int i = 0; i < n; i++)
      for(int j = 0; j < n; j++)
        sums[c++] = A[i] + B[j];
    sort(sums, sums+c);
    long long cnt = 0;
    for(int i = 0; i < n; i++)
      for(int j = 0; j < n; j++)
        cnt += upper_bound(sums, sums+c, -C[i]-D[j]) - lower_bound(sums, sums+c, -C[i]-D[j]);
    printf("%lld\n", cnt);
    if(T) printf("\n");
  }
  return 0;
}

思路

1.中途相遇法。此题暴力法,直接选四个数即可,也就是 O ( n 4 ) 的复杂度。
稍微改进,在最后一步二分查找,有 O ( n 3 l o g n ) 的复杂度。
但通过中途相遇,可以实现到 O ( 2 n 2 l o g n ) 的转化。
2.从一个数组中获得某个元素的count的方法

// 上界减下界,直接减
upper_bound(A, A+n, element) - lower_bound(A, A+n, element);

3.我自己用map做,惨遭卡常。。。只能搬过来LRJ的了。

猜你喜欢

转载自blog.csdn.net/icecab/article/details/80486783