-
Notifications
You must be signed in to change notification settings - Fork 1
/
class-03.Rmd
633 lines (499 loc) · 16.1 KB
/
class-03.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
---
title: "Class 03: Standard Template Library"
date: "01-13-2020"
---
```{r setup, include=FALSE}
htmltools::tagList(rmarkdown::html_dependency_font_awesome())
```
> "Don't reinvent the wheel!"
<div class="topic">Standard Template Library (STL) </div>
STL is a collection of libraries of C++ that we can use in the contests. It
gives us common data structures (array, stack, set, priority_queue, map, ...),
common algorithms (sort, next_permutation, binary_search, lower_bound,
upper_bound), common functions (input-output (I/O), sqrt, pow, abs, min, max, ...)
First of all, lets understand what happens in a simple hello world program.
```c++
#include <bits/stdc++.h>
using namespace std;
int main () {
cout << "Hello World!" << '\n';
return 0;
}
```
(The explanation will be given in class)
Extra: You can also practice competitive programming in other languages.
Examples:
- [Petr](https://codeforces.com/submissions/Petr/page/3)
- [pajenegod](https://codeforces.com/submissions/pajenegod)
But, as mentioned in the first class, C++ is usually better for its efficiency
and simplicity.
<div class="topic">Numeric data types and its operations</div>
### Tipos de datos enteros
- `int` $[-2^{31}, 2^{31}) \approx [-10^9, 10^9]$
- `long long` $[-2^{63}, 2^{63}) \approx [-10^{18}, 10^{18}]$
### Tipos de datos flotantes
- float
- double
- long double
### Operaciones aritméticas
- addition: x + y
- subtraction: x - y
- multiplication: x * y (what happen if $x = y = 10^9$ and `x` and `y` are `int` ?)
- division: x / y (take care if `x`, `y` are `int` and you want the result in `float`)
- exponenciation: pow(x, y) (the output is in `double`)
- module: a % b (what happen if `b` is zero? why?)
### Order or precedence
$$int < long\ long < float < double < long\ double$$
Examples:
```c++
int x = 1;
long long y = 8;
auto z = x + y; // long long
```
```c++
int x = 1;
float y = 8;
auto z = x + y; // float
```
<div class="topic">String</div>
Another useful data type is `string`.
In [cplusplus.com](http://www.cplusplus.com/reference/string/string/) you will
find a reference of how to work with strings.
[Example](./code/class-03/string.cpp)
```c++
string s;
// input
cin >> s; // In the same way you can read a int, long long, float, ...
// You can iterate it in this way
for (int i = 0; i < s.size(); i++) {
// s[i]: get the i-th element
cout << s[i] << '\n'; // In the same way you can output a int, long long, float, ...
}
s[2] = 'b'; // modify the element in position 2
// You can also print the whole string
cout << s << '\n';
// Yout can also iterate in this way
for (char elem: s) {
cout << elem;
}
cout << '\n'; // what happen without this line ?
s += 'a'; // you can add append a letter or string
cout << s.substr(2, 2) << '\n'; // what does this function do ?
// The comparisson is like this (take care of not using just one '=' )
if (s == "hola") cout << "ok" << '\n';
```
<div class="topic">Vector</div>
You will need a vector in almost all of your contests, so its very important to
know how to use it.
In [cplusplus.com](http://www.cplusplus.com/reference/vector/vector/) you will
find a reference of how to work with vectors.
[Example](./code/class-03/vector.cpp)
```c++
vector <int> arr;
// Add a element to the end of the vector - O(1)
arr.push_back(123);
arr.push_back(987);
arr.push_back(343);
arr.push_back(134);
arr.push_back(345);
// Delete the last element - O(1)
arr.pop_back();
// Insert a element in the i-th position - O(n)
int i = 2;
arr.insert(begin(arr) + i, 234);
// Delete a element in the i-th position - O(n)
i = 1;
arr.erase(begin(arr) + i);
// Copy the vector - O(n)
vector <int> arrCopy = arr;
// We can iterate a vector in this way
for (int arr_i: arr) {
// do something
}
// We can also use 'auto'
for (auto elem: arr) {
cout << elem << '\n';
}
// We can also iterate in this way
// arr.size() returns the number of element of the vector - O(1)
for (int i = 0; i < arr.size(); i++) {
// arr[i]: get the i-th element - O(1)
cout << arr[i] << '\n';
}
// Delete all the elements - O(n)
arr.clear();
```
You can find the more common methods of vectors and its complexity in this image.
<div class="row text-center">
![](./images/class-03/vector.png)
</div>
A [deque](http://www.cplusplus.com/reference/deque/deque/) gives us all the
methods of a vector and two more:
- push_front: insert a element in the begining O(1)
- pop_front: erase the first element O(1)
Read what these functions do:
* [`min_element`](http://www.cplusplus.com/reference/algorithm/min_element/)
* [`sort`](http://www.cplusplus.com/reference/algorithm/sort/)
* [`fill`](http://www.cplusplus.com/reference/algorithm/fill/)
* [`reverse`](http://www.cplusplus.com/reference/algorithm/reverse/)
* [`random_shuffle`](http://www.cplusplus.com/reference/algorithm/random_shuffle/)
* [`unique`](http://www.cplusplus.com/reference/algorithm/unique/)
* [`count`](http://www.cplusplus.com/reference/algorithm/count/)
Question: How would you declare a matrix ?
<div class="topic">Set</div>
In [cplusplus.com](http://www.cplusplus.com/reference/set/set/) you will find
a reference of how to work with sets.
[Example](./code/class-03/set.cpp)
```c++
set <int> S;
// Insert a element - O(log n)
S.insert(3);
S.insert(4);
S.insert(-100);
S.insert(-345);
// The elements are stored in ascending order
for (auto x: S) {
cout << x << endl;
}
// Check if a element is in the set - O(log n)
if (S.count(4) > 0) {
cout << "4 is in S\n";
}
// You can also check that using the method find
if (S.find(4) != end(S)) {
cout << "4 is in S" << endl;
}
// Delete a elemento - O(log n)
S.erase(4);
// You can also delete in this way
S.erase(S.find(-100));
// If we store the iterator - O(log n)
// auto it = S.find(val) - O(log n)
// Then we can erase the element - O(1)
// S.erase(it)
```
You can find the more common methods of sets and its complexity in this image.
<div class="row text-center">
![](./images/class-03/set.png)
</div>
Read about [multisets](http://www.cplusplus.com/reference/set/multiset/).
<div class="topic">Map</div>
In [cplusplus.com](http://www.cplusplus.com/reference/map/map/) you will find
a reference of how to work with maps.
[Example](./code/class-03/map.cpp)
```c++
map <string, int> my_map;
// Insert a element - O(log n)
my_map["hola"] = 1;
my_map["mundo"] = 5;
// The elements are stored in ascending order
for (auto x: my_map) {
cout << x.first << ' ' << x.second << endl;
}
// Check if a element is in the map - O(log n)
if (my_map.count("hola") > 0) {
cout << "4 is in my_map\n";
}
// You can also check that using the method find
if (my_map.find("hola") != end(my_map)) {
cout << "4 is in my_map" << endl;
}
my_map["hola"] = 10;
for (auto x: my_map) {
cout << x.first << ' ' << x.second << '\n';
}
// Delete a elemento - O(log n)
my_map.erase("hola");
// You can also delete in this way
my_map.erase(my_map.find("mundo"));
// If we store the iterator - O(log n)
// auto it = my_map.find(val) - O(log n)
// Then we can erase the element - O(1)
// my_map.erase(it)
```
The complexity of its operations is the same of a set.
<div class="topic">Struct</div>
With a `struct` we can create our own data type which can encapsulate other
data types.
[Example](./code/class-03/struct.cpp)
```c++
#include <bits/stdc++.h>
using namespace std;
struct MyStructure {
// we can declare attributes of different types
int var1;
double var2;
string var3;
MyStructure (int var1, double var2, string _var3):
var1(var1),
var2(var2) { // we can initialize the variables in this way
var3 = _var3; // ot in this way
}
void my_method () {
cout << var1 << ' ' << var2 << ' ' << var3 << '\n';
}
};
int main () {
MyStructure structure(18, 20.7, "hello world!");
structure.my_method(); // cal a method
structure.var1 = 19; // access an attribute
cout << structure.var3 << '\n';
return (0);
}
```
Read about [pair](http://www.cplusplus.com/reference/utility/pair/).
Recommended readings:
- [Antti Laaksonen.Competitive programmer’s handbook - chapter 1 and 4](https://jadi.net/wp-content/uploads/2017/07/competetive-programmers-handbook.pdf)
- [Competitive C++ Manifesto: A Style Guide](https://codeforces.com/blog/entry/64218)
- [TopCoder - Power up C++ with the Standard Template Library - Part
I](https://www.topcoder.com/community/competitive-programming/tutorials/power-up-c-with-the-standard-template-library-part-1/)
<div class="topic" id="contest">Contest</div>
You can find the contest [here](https://vjudge.net/contest/351569).
<!-- Begins problem A -->
<div class="card">
<div class="collapsed solution-title" type="button" data-toggle="collapse" data-target="#collapseProblemA" aria-expanded="false" aria-controls="collapseTwo">
<!-- title -->
<i class="fas fa-caret-right"></i> <p class="title">A: Chat Server's Outgoing Traffic</p>
</div>
<!-- begin body -->
<div id="collapseProblemA" class="collapse">
<div class="card-body solution-body">
### <a href="https://codeforces.com/contest/5/problem/A" target="_blank">Problem A: Chat Server's Outgoing Traffic</a>
Just implement what the problem says.
<!-- begin code -->
<div class="collapsed code-title" type="button" data-toggle="collapse" data-target="#codeProblemA" aria-expanded="false" aria-controls="collapseTwo">
<!-- title -->
<i class="fas fa-caret-right"></i> <p class="title">Code</p>
</div>
<div id="codeProblemA" class="collapse">
```c++
#include <bits/stdc++.h>
#define all(A) begin(A), end(A)
#define rall(A) rbegin(A), rend(A)
#define sz(A) int(A.size())
#define pb push_back
#define mp make_pair
using namespace std;
typedef long long ll;
typedef pair <int, int> pii;
int main () {
ios::sync_with_stdio(false); cin.tie(0);
int ans = 0;
int cur = 0;
string s;
while (getline(cin, s)) {
if (s[0] == '+') {
cur++;
} else if (s[0] == '-') {
cur--;
} else {
int pos = 0;
while (s[pos] != ':') pos++;
ans += (sz(s) - pos - 1) * cur;
}
}
cout << ans << '\n';
return (0);
}
```
</div>
<!-- ends code -->
</div>
</div>
</div>
<!-- ends problem A -->
<!-- Begins problem B -->
<div class="card">
<div class="collapsed solution-title" type="button" data-toggle="collapse" data-target="#collapseProblemB" aria-expanded="false" aria-controls="collapseTwo">
<!-- title -->
<i class="fas fa-caret-right"></i> <p class="title">B: Counting-out Rhyme</p>
</div>
<!-- begin body -->
<div id="collapseProblemB" class="collapse">
<div class="card-body solution-body">
### <a href="https://codeforces.com/problemset/problem/792/B" target="_blank">Problem B: Counting-out Rhyme</a>
The constraints are small, just simulate what the problem says.
<!-- begin code -->
<div class="collapsed code-title" type="button" data-toggle="collapse" data-target="#codeProblemB" aria-expanded="false" aria-controls="collapseTwo">
<!-- title -->
<i class="fas fa-caret-right"></i> <p class="title">Code</p>
</div>
<div id="codeProblemB" class="collapse">
```c++
#include <bits/stdc++.h>
#define all(A) begin(A), end(A)
#define rall(A) rbegin(A), rend(A)
#define sz(A) int(A.size())
#define pb push_back
#define mp make_pair
using namespace std;
typedef long long ll;
typedef pair <int, int> pii;
int main () {
ios::sync_with_stdio(false); cin.tie(0);
int n, k;
cin >> n >> k;
vector <int> arr(n);
iota(all(arr), 1);
int cur = 0;
for (int i = 0; i < k; i++) {
int a;
cin >> a;
a %= sz(arr);
while (a--) cur = (cur + 1) % sz(arr);
cout << arr[cur] << ' ';
arr.erase(begin(arr) + cur);
cur %= sz(arr);
}
return (0);
}
```
</div>
<!-- ends code -->
</div>
</div>
</div>
<!-- ends problem B -->
<!-- Begins problem C -->
<div class="card">
<div class="collapsed solution-title" type="button" data-toggle="collapse" data-target="#collapseProblemC" aria-expanded="false" aria-controls="collapseTwo">
<!-- title -->
<i class="fas fa-caret-right"></i> <p class="title">C: Shuffle Hashing</p>
</div>
<!-- begin body -->
<div id="collapseProblemC" class="collapse">
<div class="card-body solution-body">
### <a href="https://codeforces.com/problemset/problem/1278/A" target="_blank">Problem C: Shuffle Hashing</a>
If you can construct `h` from `p`, then $\exists s_1, s_2, q \mid h = s_1 + q + s_2$
Then $h[n:n + m] = q$ where `n` is the length $s_1$ and `m` the length of`p`.
Then $sort(h[n:n + m]) = sort(p)$.
So, we just need to check if that is true for some value of $n$.
<!-- begin code -->
<div class="collapsed code-title" type="button" data-toggle="collapse" data-target="#codeProblemC" aria-expanded="false" aria-controls="collapseTwo">
<!-- title -->
<i class="fas fa-caret-right"></i> <p class="title">Code</p>
</div>
<div id="codeProblemC" class="collapse">
```c++
#include <bits/stdc++.h>
#define all(A) begin(A), end(A)
#define rall(A) rbegin(A), rend(A)
#define sz(A) int(A.size())
#define pb push_back
#define mp make_pair
using namespace std;
typedef long long ll;
typedef pair <int, int> pii;
int main () {
ios::sync_with_stdio(false); cin.tie(0);
int tc;
cin >> tc;
while (tc--) {
string p, h;
cin >> p >> h;
bool ok = false;
sort(all(p));
for (int i = 0; i < sz(h); i++) {
string x = h.substr(i, sz(p));
sort(all(x));
if (x == p) ok = true;
}
if (ok) cout << "YES\n";
else cout << "NO\n";
}
return (0);
}
```
</div>
<!-- ends code -->
</div>
</div>
</div>
<!-- ends problem C -->
<!-- Begins problem D -->
<div class="card">
<div class="collapsed solution-title" type="button" data-toggle="collapse" data-target="#collapseProblemD" aria-expanded="false" aria-controls="collapseTwo">
<!-- title -->
<i class="fas fa-caret-right"></i> <p class="title">D: Free spots</p>
</div>
<!-- begin body -->
<div id="collapseProblemD" class="collapse">
<div class="card-body solution-body">
### <a href="https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1644" target="_blank">Problem D: Free spots</a>
For each test we can create a matrix of booleans initialized of false's. Then,
for each query $x_1, y_1, x_2, y_3$ we set to true every element of the matrix in
position $(r, c) \mid x_1 \leq r \leq x_2 \land y_1 \leq c \leq y_2$, assumming $x_1
\leq x_2 \land y_1 \leq y_2$. So, after processing every query, the answer is
the number of elements that are false.
<!-- begin code -->
<div class="collapsed code-title" type="button" data-toggle="collapse" data-target="#codeProblemD" aria-expanded="false" aria-controls="collapseTwo">
<!-- title -->
<i class="fas fa-caret-right"></i> <p class="title">Code</p>
</div>
<div id="codeProblemD" class="collapse">
```c++
#include <bits/stdc++.h>
#define all(A) begin(A), end(A)
#define rall(A) rbegin(A), rend(A)
#define sz(A) int(A.size())
#define pb push_back
#define mp make_pair
using namespace std;
typedef long long ll;
typedef pair <int, int> pii;
int main () {
ios::sync_with_stdio(false); cin.tie(0);
int w, h, n;
while (cin >> w >> h >> n) {
if (w == 0 and h == 0 and n == 0) break;
vector <vector <bool>> vis(w + 1, vector <bool> (h + 1, false));
while (n--) {
int x1, y1, x2, y2;
cin >> x1 >> y1 >> x2 >> y2;
for (int r = min(x1, x2); r <= max(x1, x2); r++) {
for (int c = min(y1, y2); c <= max(y1, y2); c++) {
vis[r][c] = true;
}
}
}
int cnt = 0;
for (int r = 1; r <= w; r++) {
for (int c = 1; c <= h; c++) {
if (!vis[r][c]) cnt++;
}
}
if (cnt == 0) cout << "There is no empty spots.\n";
else if (cnt == 1) cout << "There is one empty spot." << '\n';
else cout << "There are " << cnt << " empty spots.\n";
}
return (0);
}
```
</div>
<!-- ends code -->
</div>
</div>
</div>
<!-- ends problem D -->
<p style="float: none; clear: both;"></p>
<div style="float: right;" class="pt-3">
<a class="continue-link" href="./class-04.html"
data-toggle="tooltip" title="Complete Search I">
Next
</a>
</div>
<div class="pt-3">
<a class="continue-link" href="./class-02.html"
data-toggle="tooltip" title="Asymptotic Analysis">
Previous
</a>
</div>
<script>
$('#all-classes').collapse('show');
$('#class-03').addClass('active');
const cur_class = document.getElementById('class-03');
cur_class.scrollIntoView({
behavior: 'smooth',
block: 'center'
});
</script>