链接:http://acm.hdu.edu.cn/showproblem.php?pid=2141
题意:给出三个数列a,b,c和一组数x,求对于每个x是否存在 ai + bj + ck = x;其中三个数列最多各有500个数,x最多有1000个。
思路: 将数列a,b两两相加,组成一个数列(500*500)。
然后枚举数列c,利用二分从合并数列中查找满足条件的数。
注意事项:二分循环的条件为while(left<right) ,所以若跳出循环后left==right,要加一组判断。if(left==right && c[i]+d[left]==x) flag = 1;
1 #include <cstdio>
2 #include <cstring>
3 #include <algorithm>
4 using namespace std;
5 #define N 505
6 #define S 1005
7
8 int a[N],b[N],c[N],d[N*N];
9
10 int main()
11 {
12 int l, n, m, s, x, Case = 0;
13 while(scanf("%d%d%d",&l,&n,&m)!=EOF)
14 {
15 printf("Case %d: ",++Case);
16 for(int i=1; i<=l; i++)
17 scanf("%d",&a[i]);
18 for(int i=1; i<=n; i++)
19 scanf("%d",&b[i]);
20 for(int i=1; i<=m; i++)
21 scanf("%d",&c[i]);
22 int num = 0;
23 for(int i=1; i<=l; i++)
24 {
25 for(int j=1; j<=n; j++)
26 d[++num] = a[i] + b[j];
27 }
28 sort(d+1,d+num+1);
29 scanf("%d",&s);
30 while(s--)
31 {
32 scanf("%d",&x);
33 int flag = 0;
34 for(int i=1; i<=m; i++)
35 {
36 int left = 1, right = num, mid;
37 while(left<right)
38 {
39 mid = (left + right) / 2;
40 if(c[i]+d[mid]==x)
41 {
42 flag = 1;
43 break;
44 }
45 if(c[i]+d[mid]>x)
46 right = mid - 1;
47 else
48 left = mid + 1;
49 }
50 if(left==right && c[i]+d[left]==x) flag = 1;
51 if(flag==1) break;
52 }
53 if(flag == 1)
54 printf("YES ");
55 else
56 printf("NO ");
57 }
58 }
59 return 0;
60 }
2 #include <cstring>
3 #include <algorithm>
4 using namespace std;
5 #define N 505
6 #define S 1005
7
8 int a[N],b[N],c[N],d[N*N];
9
10 int main()
11 {
12 int l, n, m, s, x, Case = 0;
13 while(scanf("%d%d%d",&l,&n,&m)!=EOF)
14 {
15 printf("Case %d: ",++Case);
16 for(int i=1; i<=l; i++)
17 scanf("%d",&a[i]);
18 for(int i=1; i<=n; i++)
19 scanf("%d",&b[i]);
20 for(int i=1; i<=m; i++)
21 scanf("%d",&c[i]);
22 int num = 0;
23 for(int i=1; i<=l; i++)
24 {
25 for(int j=1; j<=n; j++)
26 d[++num] = a[i] + b[j];
27 }
28 sort(d+1,d+num+1);
29 scanf("%d",&s);
30 while(s--)
31 {
32 scanf("%d",&x);
33 int flag = 0;
34 for(int i=1; i<=m; i++)
35 {
36 int left = 1, right = num, mid;
37 while(left<right)
38 {
39 mid = (left + right) / 2;
40 if(c[i]+d[mid]==x)
41 {
42 flag = 1;
43 break;
44 }
45 if(c[i]+d[mid]>x)
46 right = mid - 1;
47 else
48 left = mid + 1;
49 }
50 if(left==right && c[i]+d[left]==x) flag = 1;
51 if(flag==1) break;
52 }
53 if(flag == 1)
54 printf("YES ");
55 else
56 printf("NO ");
57 }
58 }
59 return 0;
60 }