题意:给定4个n(1≤n≤4000)元素集合A,B,C,D,要求分别从中选取一个元素a,b,c,d,使得a+b+c+d=0。 问:有多少种选法?
思路1:按照紫书的思路中途相遇,就是先将a+b的所有值算出排序(二分需要),然后再枚举 -(c+d) 的所有值在a+b的数组中二分查找,如果查找到就计数。
但是还有一种情况,就是a+b的数组中有相同的值,例如以下数据:
2
0 1 0 -1
1 0 -1 0
这组的话a+b:{0,1,1,2} ,当-(c+d)的值算出-1时是需要和a+b中的俩个1都可以组合,所有有俩个,所有要将相同的情况都算出。
我的思路是利用二分查找到位置后,再从本位置左右扫描一遍,如果有相等的都累计。
参考:紫书-例8-3-P237
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
const int maxn = 4000 + 5;
const int col = 4;
LL arr[maxn][col],before[maxn*maxn];
int n,cnt;
inline void pretreat(){//预处理将a+b放入数组中后递增排序
cnt = 0;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
before[cnt++] = arr[i][0] + arr[j][1];
sort(before,before+cnt);
}
LL binarySearch(LL left,LL right,LL target){
while(left < right){
int pos = left + (right - left)/2;
if(target == before[pos])return pos;
else if(target < before[pos]) right = pos;
else left = pos + 1;
}
return -123456;
}
inline int LRSearch(int pos,int value){//寻找当数字的相同数字
int cot = 0;
for(int i=pos-1;i>=0;i--) if(before[i] == value) cot++;else break;
for(int i=pos+1;i<cnt;i++) if(before[i] == value) cot++;else break;
return cot;
}
inline void operate(){
int ansCnt = 0;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++){
LL s = arr[i][2] + arr[j][3];//计算c+d
int index = binarySearch(0,cnt,-s);//在a+b中二分查找-(c+d)返回下标
if(index != -123456){//找到
ansCnt++;//累计
ansCnt += LRSearch(index,-s);//加上相同的
}
}
printf("%d\n",ansCnt);
}
int main()
{
int t;
scanf("%d",&t);
while(t--){
scanf("%d",&n);
for(int i=0;i<n;i++)
for(int j=0;j<col;j++) scanf("%lld",&arr[i][j]);
pretreat();
operate();
if(t) printf("\n");
}
return 0;
}
思路2:看了紫书代码库后,才知道用二分的上下界求出数组中有多少个相同的值即可:上界位置 - 下界位置 = 相同的个数。
参考:紫书代码库
代码:
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long LL;
const int maxn = 4000 + 5;
const int col = 4;
LL arr[maxn][col],before[maxn*maxn];
int n,cnt;
inline void pretreat(){//预处理将a+b放入数组中后递增排序
cnt = 0;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
before[cnt++] = arr[i][0] + arr[j][1];
sort(before,before+cnt);
}
inline void operat(){
LL ans = 0,value;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++){
value = -(arr[i][2] + arr[j][3]);
ans += upper_bound(before,before+cnt,value) - lower_bound(before,before+cnt,value);//将-(c+d)的上下界求出后上界-下界即得出当前数出现几次了。
}
printf("%lld\n",ans);
}
int main()
{
int t;
scanf("%d",&t);
while(t--){
scanf("%d",&n);
for(int i=0;i<n;i++)
for(int j=0;j<col;j++) scanf("%lld",&arr[i][j]);
pretreat();
operat();
if(t) printf("\n");
}
return 0;
}