标签:des style http io color ar os sp for
Description
The SUM problem can be formulated as follows: given four lists A, B, C, D of integer values, compute how many quadruplet (a, b, c, d ) AxBxCxD are such that a + b + c + d = 0 . In the following, we assume that all lists have the same size n .
The input begins with a single positive integer on a line by itself indicating the number of the cases following, each of them as described below. This line is followed by a blank line, and there is also a blank line between two consecutive inputs.
The first line of the input file contains the size of the lists
n (this value can be as large as 4000). We then have
n lines containing four integer values (with absolute value as large as
228 ) that belong respectively to
A, B, C and D .
For each test case, the output must follow the description below. The outputs of two consecutive cases will be separated by a blank line.
For each input file, your program has to write the number quadruplets whose sum is zero.
1 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
Sample Explanation: Indeed, the sum of the five following quadruplets is zero: (-45, -27, 42, 30), (26, 30, -10, -46), (-32, 22, 56, -46),(-32, 30, -75, 77), (-32, -54, 56, 30).
# include <algorithm>中:
upper_bound(a, a+n, x);在左闭右开区间a到a+n地址之间;找到大于x的最小值的位置:
lower_bound(a, a+n,x) ;在左闭右开区间a到a+n地址之间;找到大于或等于的值的位置;
//方法一:二分法求解;
# include <cstdio> # include <string> # include <cstring> # include <iostream> # include <algorithm> using namespace std; int a[4005],b[4005],c[4005],d[4005]; int sum[16000025],sum2[16000025]; int main() { int t; cin>>t; while(t--) { int n,i,j,len=0,ans=0;; cin>>n; for(i=0;i<n;i++) scanf("%d%d%d%d",&a[i],&b[i],&c[i],&d[i]); for(i=0;i<n;i++) for(j=0;j<n;j++) sum[len++]=a[i]+b[j]; len=0; for(i=0;i<n;i++) for(j=0;j<n;j++) sum2[len++]=c[i]+d[j]; sort(sum2,sum2+len); for(i=0;i<len;i++) { int l=0,r=len-1,mid; while(l<r) { mid=(r+l)>>1; if(sum[i]<-sum2[mid]) l=mid+1; else r=mid; } while(sum2[l]==-sum[i]&&l<len) { ans++; l++; } } printf("%d\n",ans); if(t) printf("\n"); } return 0; } //方法二:用函数upper_boud(),lower_boud()代替二分: # include <iostream> # include <cstdio> # include <algorithm> using namespace std; int a[4005],b[4005],c[4005],d[4005]; int sum[16000005]; int main() { int t; cin>>t; while(t--) { int n,i,j,cnt=0,ans=0; cin>>n; for(i=0;i<n;i++) scanf("%d%d%d%d",&a[i],&b[i],&c[i],&d[i]); for(i=0;i<n;i++) for(j=0;j<n;j++) sum[cnt++]=a[i]+b[j]; sort(sum,sum+cnt); for(i=0;i<n;i++) for(j=0;j<n;j++) ans+=upper_bound(sum,sum+cnt,-c[i]-d[j])-lower_bound(sum,sum+cnt,-c[i]-d[j]); printf("%d\n",ans); if(t!=0) printf("\n"); } return 0; }
标签:des style http io color ar os sp for
原文地址:http://blog.csdn.net/rechard_chen/article/details/41017557