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 ) ∈ A x B x C x D are such that a + b + c + d = 0 . In the following, we assume that all lists have the same size n .
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 2 28 ) that belong respectively to A, B, C and D .
For each input file, your program has to write the number quadruplets whose sum is zero.
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
Sample Output
5
HintSample 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).
题意为从给出的四列数中,每列选出一个数,可以重复选,问有多少组这四个数相加结果等于0。
每列的个数最多四千 ,暴力4000^4,一定超时的。我们中的巨巨想到一个办法。先将数组预处理下两个两个合并,前两个合并,后两个合并。这样新生成的两个数组,第一个为前两列各个数字的和,第二个为后两列各个数字的和。这样的复杂度为O(n^2),16000000,这样不会超时,接下来遍历其中一个数组,二分另外一个数组,如果遍历的那个数组元素的相反数等于,在另外的一个数组中二分找到了,ans++;
这个思路是很厉害的,可是交上去一直wa,我们各种改还是不对,比赛结束后才想到,万一二分的那个数组中要查找的数出现了多次怎么办!漏洞就在这,把查找到的那个数在向两边搜下看有没有相等的就好了,注意break;我在这超时了两发~~~~~
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | #include<cstdio> #include<algorithm> using namespace std; const int maxn = 4005; const int maxnn = 16000000+25; int a[maxn],b[maxn],c[maxn],d[maxn],ab[maxnn],cd[maxnn]; int n,m,k; int s_division( int x){ int l,r,mid,ans; l = 0; r = m-1; mid = ans = 0; while (l<=r){ mid=(l+r)>>1; if (cd[mid]==x){ ans++; for ( int j=mid+1;j<m;j++){ if (cd[mid]==cd[j]) ans++; else break ; } for ( int j=mid-1;j>=0;j--){ if (cd[mid]==cd[j]) ans++; else break ; } return ans; } if (cd[mid]<x) l=mid+1; if (cd[mid]>x) r=mid-1; } return ans; } int main(){ int n,sum; while ( scanf ( "%d" ,&n)==1){ sum = 0;k = m = 0; for ( int i=0;i<n;i++){ scanf ( "%d %d %d %d" ,&a[i],&b[i],&c[i],&d[i]); } for ( int i=0;i<n;i++){ for ( int j=0;j<n;j++){ ab[k++]=a[i]+b[j]; } } for ( int i=0;i<n;i++){ for ( int j=0;j<n;j++){ cd[m++]=c[i]+d[j]; } } sort(cd,cd+m); for ( int i=0;i<k;i++){ sum+=s_division(-1*ab[i]); } printf ( "%d\n" ,sum); } return 0; } |
贵在坚持 难在坚持 成在坚持
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步