P1678 trouble College Entrance Examination

P1678 exam Links: https://www.luogu.org/problem/P1678

Difficulty: universal -

Algorithms Tags: analog, greedy, sort, binary search

1. Simple analog O (m * n) Score 30

First of m school admission order, then each candidate's results in order to find the i-th university (if a university admission scores greater than or equal results of the candidates, is the i-th University), the results of the candidates in i-1 th first admission line between the i-th and universities, with admission of the i-1 th and i-th University subtracting the results of the candidates, respectively, absolute value, minimum value as required, with the both the smaller value plus the sum of the absolute value, the final answer is the sum

 1 #include <cstdio>
 2 #include <algorithm>
 3 using namespace std;
 4 int m, n, a[100010], b[100010];
 5 int main()
 6 {
 7     scanf("%d%d", &m, &n);
 8     int sum = 0;
 9     for(int i = 0; i < m; ++i)
10         scanf("%d", &a[i]);
11     for(int i = 0; i < n; ++i)
12         scanf("%d", &b[i]);
13     sort(a, a + m);
14     for(int i = 0; i < n; ++i)
15     {
16         for(int j = 0; j < m; ++j)
17         {
18             if(b[i] <= a[j])
19             {
20                 if(j == 0) sum += a[0] - b[i];
21                 else sum += min(abs(a[j] - b[i]), abs(a[j - 1] - b[i]));
22                 break;
23             }
24         }
25     }
26     printf("%d\n", sum);
27     return 0;
28 } 

2. The binary search optimization O (log (m) * n) Score 100

Use binary search to find the i-th University of each candidate, the search process requires only log (m) times, can solve the larger problem of time complexity, the rest of empathy with the simple algorithm

 1 #include <cstdio>
 2 #include <algorithm>
 3 using namespace std;
 4 int m, n, a[100010], b[100010];
 5 int main()
 6 {
 7     scanf("%d%d", &m, &n);
 8     int sum = 0;
 9     for(int i = 0; i < m; ++i)
10         scanf("%d", &a[i]);
11     for(int i = 0; i < n; ++i)
12         scanf("%d", &b[i]);
13     sort(a, a + m);
14     for(int i = 0; i < n; ++i)
15     {
16         int l = 0, r = m - 1;
17         while(l < r)
18         {
19             int mid = (l + r) / 2;
20             if(b[i] >= a[mid]) l = mid + 1;
21             else if(b[i] < a[mid]) r = mid;
22         }
23         if(b[i] <= a[0]) sum += a[0] - b[i];
24         else sum += min(abs(a[l - 1] - b[i]), abs(a[l] - b[i]));
25     }
26     printf("%d\n", sum);
27     return 0;
28 } 

Guess you like

Origin www.cnblogs.com/ZhangRunqi/p/11297431.html