题目链接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=246&page=show_problem&problem=3593
分析:求a+b+c+d=0。分别枚举a+b,-c-d。和书上的思想一样。
#include<stdio.h> #include<iostream> #include<algorithm> using namespace std; const int maxn = 4000 + 10; int a[maxn],b[maxn],c[maxn],d[maxn],ab[maxn*maxn]; int main(){ int T; cin >> T; while(T--){ int N; cin >> N; for(int i=0;i<N;i++){ cin>>a[i]>>b[i]>>c[i]>>d[i]; } for(int i=0;i<N;i++) for(int j=0;j<N;j++) ab[i*N+j]=a[i]+b[j]; sort(ab,ab+N*N); long long cnt=0;//用int也能过,不过还是要注意一下,毕竟在比赛中犯过同样的错误 for(int i=0;i<N;i++){ for(int j=0;j<N;j++){ cnt+=upper_bound(ab,ab+N*N,-c[i]-d[j]) - lower_bound(ab,ab+N*N,-c[i]-d[j]); } } printf("%lld\n",cnt); if(T) printf("\n"); } return 0; }
汝佳提供的代码:
// UVa1152 4 Values Whose Sum is Zero // Rujia Liu #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; }