UVA-1152-4 Values whose Sum is 0---中途相遇法

题目链接:

https://cn.vjudge.net/problem/UVA-1152

题目大意:

给出4个数组,每个数组有n个数,问有多少种方案在每个数组中选一个数,使得四个数相加为0.

n <= 4000

解题思路:

两重循环求出a + b的所有情况

两重循环求出-c - d的所有情况

枚举a+b的值,在-c-d里面找相同值的数目即可。

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<iostream>
 4 #include<algorithm>
 5 #include<string>
 6 #include<cmath>
 7 #include<set>
 8 #include<queue>
 9 #include<map>
10 #include<stack>
11 #include<vector>
12 #include<list>
13 #include<deque>
14 using namespace std;
15 typedef long long ll;
16 const int maxn = 1e6 + 10;
17 const double eps = 1e-6;
18 const int INF = 1 << 30;
19 int T, n, m;
20 int a[4005], b[4005], c[4005], d[4005];
21 int ab[16001000], cd[16001000];
22 int main()
23 {
24     scanf("%d",&T);
25     while(T--)
26     {
27         scanf("%d",&n);
28         for(int i = 0; i < n; i++)
29         {
30             scanf("%d%d%d%d",&a[i],&b[i],&c[i],&d[i]);
31         }
32         int tot = 0, ans = 0;
33         for(int i = 0; i < n; i++)
34         {
35             for(int j = 0; j < n; j++)
36             {
37                 ab[tot] = a[i] + b[j];
38                 cd[tot++] = c[i] + d[j];
39             }
40         }
41         sort(ab, ab + tot);
42         for(int i = 0; i < tot; i++)
43             ans += upper_bound(ab, ab + tot, -cd[i]) - lower_bound(ab, ab + tot, -cd[i]);
44         cout<<ans<<endl;
45         if(T)cout<<endl;
46     }
47     return 0;
48 }

猜你喜欢

转载自www.cnblogs.com/fzl194/p/9320999.html