题意:
输入一个 n 行四列的矩阵,每一列取一个数,总共取四个数,求有多少种可能的四个数相加和为0。
思路:
枚举
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int n, a1[5][4010], b1[4001*4001], s[4001*4001], cnt[4001*4001];
int p = 0, p2 = 0, ans;
int main(){
scanf("%d", &n);
for(int i = 1; i <= n; i ++)
for(int j = 1; j <= 4; j ++)
scanf("%d", &a1[j][i]);
for(int i = 1; i <= n; i ++)
for(int j = 1; j <= n; j ++)
b1[++p] = a1[1][i] + a1[2][j];
sort(b1+1, b1+1+p);
s[0] = 1e9;
for(int i = 1; i <= p; i ++){
if(b1[i] == s[p2]) cnt[p2] ++;
else s[++p2] = b1[i], cnt[p2] = 1;
}
for(int i = 1; i <= n; i ++){
for(int j = 1; j <= n; j ++){
int val = -(a1[3][i]+a1[4][j]);
int l = 1, r = p2;
while(l <= r){
int mid = (l+r)>>1;
if(s[mid] == val){
ans += cnt[mid];
break;
}
if(s[mid] < val) l = mid + 1;
else r = mid - 1;
}
}
}
printf("%d", ans);
return 0;
}