C. Letters (prefix and, binary lookup)

Keywords: PHP

Title Link: http://codeforces.com/problemset/problem/978/C

 

What's the meaning of the title: tell you several dormitories, and then how many rooms there are in each dormitories. The number of each room is added up from the first one at a time. Now I'll give you some envelopes with only the room number on them. Now let's judge which dormitories this room belongs to. In this dormitories, he is the number of rooms.  

 

The first method is handwriting dichotomy:

 1 #include <cstdio>
 2 #include <string>
 3 #include <iostream>
 4 #include <algorithm>
 5 #include <cstdbool>
 6 #include <string.h>
 7 #include <math.h>
 8 
 9 
10 using namespace std;
11 
12 typedef long long LL;
13 
14 LL a[2000005];
15 LL pre[2000005];
16 
17 LL binarySearch(LL a[],LL n,LL key)
18 {
19     LL left = 1,right = n-1;
20     while (left <= right)
21     {
22         LL mid = (left + right) / 2;
23         if (a[mid] >= key)
24             right = mid - 1;
25         else if (a[mid] < key)
26             left = mid + 1;
27     }
28     return left;
29 }
30 
31 int main()
32 {
33     ios_base::sync_with_stdio(0);
34     cin.tie(NULL);
35     LL n,m;
36     cin >> n >> m;
37     for (LL i=1;i<=n;i++)
38     {
39         cin >> a[i];
40         pre[i] = pre[i-1]+a[i];
41     }
42     LL temp;
43     for (LL i=1;i<=m;i++)
44     {
45         cin >> temp;
46         LL pos = binarySearch(pre,n,temp);
47         cout << pos << ' ' << temp-pre[pos-1] << endl;
48     }
49     return 0;
50 }

 

The second method: using C + + functions

 1 #include <cstdio>
 2 #include <string>
 3 #include <iostream>
 4 #include <algorithm>
 5 #include <cstdbool>
 6 #include <string.h>
 7 #include <math.h>
 8 
 9 
10 using namespace std;
11 
12 typedef long long LL;
13 
14 LL a[2000005];
15 LL pre[2000005];
16 
17 
18 int main()
19 {
20     ios_base::sync_with_stdio(0);
21     cin.tie(NULL);
22     LL n,m;
23     cin >> n >> m;
24     for (LL i=1;i<=n;i++)
25     {
26         cin >> a[i];
27         pre[i] = pre[i-1]+a[i];
28     }
29     LL temp;
30     for (LL i=1;i<=m;i++)
31     {
32         cin >> temp;
33         LL pos = lower_bound(pre+1,pre+1+n,temp)-pre;
34         cout << pos << ' ' << temp-pre[pos-1] << endl;
35     }
36     return 0;
37 }

Posted by donbueck on Sat, 02 Nov 2019 11:39:47 -0700