2016HUAS暑假集训训练2 O

题目链接:https://vjudge.net/contest/121192#problem/O

这道题是一道典型二分搜素题,题意是给定3个数组 每个数组的数有m个 再给定l个sum要求在每个数组中是否有一个数之和等于sum   首先对每一个数组进行排序 然后把前两个集合所有情况的数加起来并保存在一个sun数组里  再对最后一个数组中的元素被sum减   得到的值再去sun数组中寻找   有的话就存在退出,因为最后一个数组的大小会小于sun数组的大小 能够节省时间

ac代码:

 1 import java.io.BufferedInputStream;
 2 import java.util.Arrays;
 3 import java.util.Scanner;
 4 
 5 public class Main {
 6     public static void main(String[] args) {
 7         Scanner s = new Scanner(new BufferedInputStream(System.in));
 8         int a, b, jj, l, j, c, i, t, t2, sum;
 9 
10         boolean f;
11         jj = 1;
12         while (s.hasNext()) {
13             a = s.nextInt();
14             b = s.nextInt();
15             c = s.nextInt();
16             int ar[] = new int[a], br[] = new int[b], cr[] = new int[c];
17             for (i = 0; i < a; i++)
18                 ar[i] = s.nextInt();
19             for (i = 0; i < b; i++)
20                 br[i] = s.nextInt();
21             for (i = 0; i < c; i++)
22                 cr[i] = s.nextInt();
23             int sun[] = new int[a * b];
24             Arrays.sort(ar);
25             Arrays.sort(br);
26             System.out.println("Case " + jj++ + ":");
27             t = s.nextInt();
28             Arrays.fill(sun, 0);
29             l = 0;
30         
31             for (i = 0; i < a; i++) {
32                 for (j = 0; j < b; j++) {
33                     {
34                         sun[l++] =  (ar[i] + br[j]);
35 
36                     }
37                 }
38             }
39             Arrays.sort(cr);
40             Arrays.sort(sun);
41             while (t-- > 0) {
42                 sum = s.nextInt();
43                 
44                 f = false;
45                  
46                     for (i = 0; i < c; i++)
47                         if ((t2 = Arrays.binarySearch(sun,sum- cr[i]))>=0) {           //java系统内部的二分查找函数
48                             f = true;
49                             break;
50                         }
51 
52                 if (f == true)
53                     System.out.println("YES");
54                 else
55                     System.out.println("NO");
56             }
57 
58         }
59         s.close();
60     }
61 }
原文地址:https://www.cnblogs.com/LIUWEI123/p/5698777.html