UVa 1152 4 Values whose Sum is 0

题意:给出n,四个集合a,b,c,d每个集合分别有n个数,分别从a,b,c,d中选取一个数相加,问使得a+b+c+d=0的选法有多少种

 

看的紫书,先试着用hash写了一下,

是用hash[]记录下来a[i]+b[j]的值,

如果a[i]+b[j]>0,hash[a[i]+b[j]]=1

如果a[i]+b[j]<0,hash[-(a[i]+b[j])]=-1

再用一个hash0[]去储存c[i]+d[j] 这样只需要满足hash[i]==1||hash0[i]==-1或者hash[i]==-1,hash0[i]==1就可以了

可是这样写过不了样例,因为在选择的过程中,不一定只有一种选择的和为i,最后可能会将本应该符合题意的hash值覆盖掉

 

 

然后学习的lrj的代码,记录下所有a[]+b[]的值,在这个序列里面找-c[i]-d[j] 有多少个

 1 #include<iostream>  

 2 #include<cstdio>  

 3 #include<cstring> 

 4 #include <cmath> 

 5 #include<stack>

 6 #include<vector>

 7 #include<map> 

 8 #include<set>

 9 #include<queue> 

10 #include<algorithm>  

11 #define mod=1e9+7;

12 using namespace std;

13 

14 typedef long long LL;

15 const int maxn=4000+5;

16 int s[maxn*maxn];

17 int a[maxn],b[maxn],c[maxn],d[maxn];

18 

19 int main(){

20     int t,n,i,j,cnt;

21     scanf("%d",&t);

22     while(t--){

23         scanf("%d",&n);

24         for(i=0;i<n;i++) scanf("%d %d %d %d",&a[i],&b[i],&c[i],&d[i]);

25         

26         int len=0;

27         for(i=0;i<n;i++){

28             for(j=0;j<n;j++)

29             s[len++]=a[i]+b[j];

30         }

31         

32         sort(s,s+len);

33         

34         cnt=0;

35         for(i=0;i<n;i++){

36             for(j=0;j<n;j++)

37             cnt += upper_bound(s,s+len, -c[i]-d[j]) - lower_bound(s,s+len, -c[i]-d[j]);

38         }

39         cout<<cnt<<"\n";

40         if(t) cout<<"\n";

41     }

42 }
View Code

 

你可能感兴趣的:(value)