-
Notifications
You must be signed in to change notification settings - Fork 1
/
class-08.Rmd
1120 lines (916 loc) · 27.2 KB
/
class-08.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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Class 08: Complete Search V"
date: "01-29-2020"
---
```{r setup, include=FALSE}
htmltools::tagList(rmarkdown::html_dependency_font_awesome())
```
> "Like the God of go"
<div class="topic">Power set</div>
The power set of a set is the set of all its subsets. For example:
$$A = \{1, 2, 3\}$$
$$P(A) = \{\emptyset, \{1\}, \{2\}, \{3\}, \{1, 2\}, \{2, 3\}, \{1, 3\}, \{1, 2, 3\} \}$$
Here $P(A)$ represents the power set of the set $A$. Moreover, we have that $|P(A)| = 2^{|A|}$.
**Extra:** In some books, $P(A)$ is written as $2^{A}$ (e.g [Motousek
- Invitation to Discrete Mathematics](https://www.amazon.com/-/es/Jiri-Matousek/dp/0198570422)).
We already know how to generate the power set of $A = \{1, 2, 3, \dots, n\}$
using bitmasks.
<!-- begin code -->
<div class="collapsed code-title" type="button" data-toggle="collapse" data-target="#codeProblembitmask" aria-expanded="false" aria-controls="collapseTwo">
<!-- title -->
<i class="fas fa-caret-right"></i> <p class="title">Code</p>
</div>
<div id="codeProblembitmask" class="collapse">
```c++
#include <bits/stdc++.h>
using namespace std;
void print (const vector <int>& arr) {
cout << "{";
bool first = true;
for (int elem: arr) {
if (!first) {
cout << ", ";
}
cout << elem;
first = false;
}
cout << "}\n";
}
int main () {
int n = 3;
for (int mask = 0; mask < (1 << n); mask++) {
vector <int> subset;
for (int bit = 0; bit < n; bit++) {
if ((mask >> bit) & 1) {
subset.push_back(bit + 1);
}
}
print(subset);
}
return (0);
}
```
</div>
<!-- ends code -->
But, we can also generate it using recursion, but before that, let's review
about passing arguments to a function in C++.
```c++
#include <bits/stdc++.h>
using namespace std;
// Here is passed a reference to 'arr' in O(1)
// You CAN read from 'arr', but you CAN NOT modify it
void f1 (const vector <int>& arr) {
}
// Here is passed a reference to 'arr' in O(1)
// You CAN read from 'arr' and you CAN modify it
void f2 (vector <int>& arr) {
}
// Here is passed a copy of 'arr' in O(n)
// You CAN read from 'arr' and you CAN modify it
// BUT, you are modifying a copy of 'arr', not the 'arr' of 'main'
void f3 (vector <int> arr) {
}
int main () {
int n = 10000;
vector <int> arr(n);
for (int i = 0; i < n; i++) {
arr[i] = i;
}
f1(arr);
f2(arr);
f3(arr);
return (0);
}
```
If we want to generate the power set of $A = \{1, 2, 3\}$, we can make
a function that follows these states:
<div class="row text-center">
![](./images/class-08/power-set.png)
</div>
That is, if we are in the state $(a_1, a_2, \dots a_x) \mid a_1 < a_2 < \dots <
a_x$, then we can go to $(a_1, a_2, \dots, a_x, a_y) \mid a_x < a_y \leq n$.
And we can implement it using recursion.
<!-- begin code -->
<div class="collapsed code-title" type="button" data-toggle="collapse" data-target="#codeProblembacktrack-power-set" aria-expanded="false" aria-controls="collapseTwo">
<!-- title -->
<i class="fas fa-caret-right"></i> <p class="title">Code</p>
</div>
<div id="codeProblembacktrack-power-set" class="collapse">
```c++
#include <bits/stdc++.h>
using namespace std;
void print (const vector <int>& arr) {
cout << "{";
bool first = true;
for (int elem: arr) {
if (!first) {
cout << ", ";
}
cout << elem;
first = false;
}
cout << "}\n";
}
void backtrack (vector <int>& arr, const int n) {
print(arr);
int ax = 0;
if (!arr.empty()) {
ax = arr.back();
}
for (int ay = ax + 1; ay <= n; ay++) {
// add ay
arr.push_back(ay);
backtrack(arr, n);
// delete ay
arr.pop_back();
}
}
int main () {
int n = 3;
vector <int> subset;
backtrack(subset, n);
}
```
</div>
<!-- ends code -->
But, in competitive programming, we usually try to have as few parameters in
our functions as possible. Then, we realize that we can implement it in this
way (**why?**).
<!-- begin code -->
<div class="collapsed code-title" type="button" data-toggle="collapse" data-target="#codeProblembacktrack-power-set-global" aria-expanded="false" aria-controls="collapseTwo">
<!-- title -->
<i class="fas fa-caret-right"></i> <p class="title">Code</p>
</div>
<div id="codeProblembacktrack-power-set-global" class="collapse">
```c++
#include <bits/stdc++.h>
using namespace std;
void print (const vector <int>& arr) {
cout << "{";
bool first = true;
for (int elem: arr) {
if (!first) {
cout << ", ";
}
cout << elem;
first = false;
}
cout << "}\n";
}
// global variables
vector <int> subset;
int n;
void backtrack () {
print(subset);
int ax = 0;
if (!subset.empty()) {
ax = subset.back();
}
for (int ay = ax + 1; ay <= n; ay++) {
// add ay
subset.push_back(ay);
backtrack();
// delete ay
subset.pop_back();
}
}
int main () {
n = 3;
backtrack();
}
```
</div>
<!-- ends code -->
Here we have implemented a program to find the power set of $\{1, 2, 3, \dots, n\}$ in
$O(n 2 ^ n)$. This is a solution using what is known as `backtracking`. In
general, a backtracking solution has this form:
```bw
let state be a global variable
T backtrack (some parameters):
if (state is a terminal state):
Do something with 'state' and return something
for (state' reachable from state):
# do something
previous = state
state = state'
backtrack(some parameters')
# reverse changes
state = previous
```
A terminal state is a state in which we can not go to other states (or it is not
convenient to follow searching).
<div class="topic">0-1 Knapsack problem</div>
**Problem:** You have a knapsack of capacity $W$ (i.e you can put at most $W$ kg in this
knapsack). Moreover, you have $n$ items. Each item is describe as a pair
$(val_i, w_i)$, where $val_i$ is the cost of the item and $w_i$ the weight of
it. Find the maximum value you can store in this knapsack using the least
possible weight.
$$1 \leq n \leq 16$$
**Solution:**
Each item can be taken or not, then we can search over all the possibilites
(power set) using bitmasks or backtracking.
<!-- begin code -->
<div class="collapsed code-title" type="button" data-toggle="collapse" data-target="#codeProblem0-1-knapsack" aria-expanded="false" aria-controls="collapseTwo">
<!-- title -->
<i class="fas fa-caret-right"></i> <p class="title">Code</p>
</div>
<div id="codeProblem0-1-knapsack" class="collapse">
```c++
#include <bits/stdc++.h>
using namespace std;
int n;
int W;
vector <int> val;
vector <int> w;
vector <int> take;
int max_sum_val = 0;
int min_sum_w = 0;
vector <int> ans_items_taken;
void backtrack (int last_taken, int sum_val, int sum_w) {
if (sum_w <= W and (sum_val > max_sum_val or
(sum_val == max_sum_val and sum_w < min_sum_w))) {
max_sum_val = sum_val;
min_sum_w = sum_w;
ans_items_taken = take;
}
for (int i = last_taken + 1; i < n; i++) {
take.push_back(i);
backtrack(i, sum_val + val[i], sum_w + w[i]);
take.pop_back();
}
}
int main () {
n = 3;
W = 10;
// item 1
val.push_back(10);
w.push_back(10);
// item 2
val.push_back(1);
w.push_back(8);
// item 3
val.push_back(13);
w.push_back(2);
backtrack(-1, 0, 0);
cout << "Take items";
for (int item: ans_items_taken) {
cout << ' ' << item + 1;
}
cout << '\n';
return (0);
}
```
</div>
<!-- ends code -->
<div class="topic">Permutations</div>
The problem of generating all the permutations can also be easily computed using
backtracking in $O(n n!)$
<!-- begin code -->
<div class="collapsed code-title" type="button" data-toggle="collapse" data-target="#codeProblempermutation" aria-expanded="false" aria-controls="collapseTwo">
<!-- title -->
<i class="fas fa-caret-right"></i> <p class="title">Code</p>
</div>
<div id="codeProblempermutation" class="collapse">
```c++
#include <bits/stdc++.h>
using namespace std;
int n;
vector <bool> used;
vector <int> permutation;
void print (const vector <int>& p) {
for (int elem: p) {
cout << elem << ' ';
}
cout << '\n';
}
void backtrack () {
if (permutation.size() == n) {
print(permutation);
return;
}
for (int p_i = 1; p_i <= n; p_i++) {
if (!used[p_i]) {
used[p_i] = true;
permutation.push_back(p_i);
backtrack();
used[p_i] = false;
permutation.pop_back();
}
}
}
int main () {
n = 3;
used.resize(n + 1, false);
backtrack();
return (0);
}
```
</div>
<!-- ends code -->
Here we are following these states:
<div class="row text-center">
![](./images/class-08/permutation.png)
</div>
This image represents what is called the **recursion tree**. It show us how the
function do the transitions.
Moreover, notice that we do not need to do something like this:
```c++
.
.
.
for (int p_i = 1; p_i <= n; p_i++) {
if (!used[p_i]) {
vector <bool> used_previous = used;
vector <int> permutation_previous = permutation;
used[p_i] = true;
permutation.push_back(p_i);
backtrack();
used = used_previous;
permutation = permutation_previous;
}
}
.
.
.
```
Because it will be heavier that the first solution and we know that:
* If previous of calling the recursion we ADD an element TO THE END of the vector, then
after the recursion we must DELETE THE LAST element of the vector.
* If previous of calling the recursion we SET TO TRUE an element, then after
the recursion we must SET TO FALSE that element.
* If previous of calling the recursion we ADD something, then after
the recursion we must SUBTRACT something.
* Following this logic, If previous of calling the recursion we DO ONE OPERATION, then after
the recursion we must REVERSE that operation. If the operation is complicated
we can just save a copy of the previous state, else we can try to reverse the
operations.
From all this one notice that if you are in your recursion in some `state` and
you go to `state'`, then after returning of traversing the recursion tree of
`state'` you expect to have some variables in the condition they were
before traversing the recursion tree of `state'`. Understanding this idea is
the key to implement backtracking solutions.
<div class="topic">Sudoku</div>
With backtracking it is easy to generate all possible movements in a game and
choose the best movement.
**Problem:**
<div class="row text-center">
![](./images/class-08/sudoku1.png)
</div>
Complete the above sudoku such that each number from 1 to 9 is found just once
in each row, column and quadrant.
**Solution:** We can just search all possible solutions using bactracking.
<!-- begin code -->
<div class="collapsed code-title" type="button" data-toggle="collapse" data-target="#codeProblemsudoku" aria-expanded="false" aria-controls="collapseTwo">
<!-- title -->
<i class="fas fa-caret-right"></i> <p class="title">Code</p>
</div>
<div id="codeProblemsudoku" class="collapse">
```c++
#include <bits/stdc++.h>
using namespace std;
vector <vector <int>> sudoku;
vector <vector <int>> sudoku_solved;
vector <vector <pair <int, int>>> quadrant;
int n;
int N;
bool found;
bool validInRow (int r, int d) {
for (int c = 0; c < N; c++) {
if (sudoku[r][c] == d) return false;
}
return true;
}
bool validInCol (int c, int d) {
for (int r = 0; r < N; r++) {
if (sudoku[r][c] == d) return false;
}
return true;
}
bool validInQuadrant (int q, int d) {
for (pair <int, int> pos: quadrant[q]) {
int r = pos.first;
int c = pos.second;
if (sudoku[r][c] == d) return false;
}
return true;
}
// run this function for every 0 <= r < N and 0 <= c < N and you will get
// what this function does
int getQuadrant (int r, int c) {
return (r / n) * n + (c / n);
}
void backtrack (int r, int c) {
if (r == N) {
found = true;
sudoku_solved = sudoku;
return;
}
if (found) {
return;
}
int nc = (c + 1 == N) ? 0 : c + 1; // new column
int nr = (c + 1 == N) ? r + 1 : r; // new row
if (sudoku[r][c] != 0) {
backtrack(nr, nc);
return;
}
for (int d = 1; d <= 9; d++) {
int quadrant = getQuadrant(r, c);
if (validInRow(r, d) and
validInCol(c, d) and
validInQuadrant(getQuadrant(r, c), d)) {
sudoku[r][c] = d;
backtrack(nr, nc);
sudoku[r][c] = 0;
}
}
}
void precomputation () {
found = false;
N = sudoku.size();
n = 1;
while ((n + 1) * (n + 1) <= N) n++;
// n = sqrt(N)
quadrant.resize(N);
for (int r = 0; r < N; r++) {
for (int c = 0; c < N; c++) {
quadrant[getQuadrant(r, c)].push_back({r, c});
}
}
}
void print (const vector <vector <int>>& sudoku) {
for (auto row: sudoku) {
for (int elem: row) {
cout << elem << ' ';
}
cout << '\n';
}
}
int main () {
sudoku = {
{3, 0, 6, 5, 0, 8, 4, 0, 0},
{5, 2, 0, 0, 0, 0, 0, 0, 0},
{0, 8, 7, 0, 0, 0, 0, 3, 1},
{0, 0, 3, 0, 1, 0, 0, 8, 0},
{9, 0, 0, 8, 6, 3, 0, 0, 5},
{0, 5, 0, 0, 9, 0, 6, 0, 0},
{1, 3, 0, 0, 0, 0, 2, 5, 0},
{0, 0, 0, 0, 0, 0, 0, 7, 4},
{0, 0, 5, 2, 0, 6, 3, 0, 0}
};
precomputation();
backtrack(0, 0);
print(sudoku_solved);
return (0);
}
```
</div>
<!-- ends code -->
With this code we get this solution:
<div class="row text-center">
![](./images/class-08/sudoku2.png)
</div>
<div class="topic">N-queen problem</div>
**[Problem:](https://www.hackerearth.com/practice/basic-programming/recursion/recursion-and-backtracking/tutorial/)** Given a chess board having $N \times N$ cells, you need to place $N$ queens on the board in such a way that no queen attacks any other queen.
$$1 \leq N \leq 10$$
**Remember:** A queen can attack in a complete row, column or diagonal.
**Solution:** We could try to place N queen in the $N \times N$ cells. In this
way we may get $\binom{N \times N}{N}$ states to check. But for $N = 8$ we have
that $\binom{N \times N}{N} \approx 8B$, so we need a better approach.
We know that each queen should be in different columns (else they will be
attacking each other). So we can generate these $N^N$ possible configurations and check
if the conditions holds, but this solution may not be enough.
We know that each queen should be in different rows and columns. Then, the rows
of the queens of a valid configuration are a permutation. The same holds for
the columns. Thereby, we have $N!$ possible configurations to check. We can
implement this idea using backtracking in this way:
<!-- begin code -->
<div class="collapsed code-title" type="button" data-toggle="collapse" data-target="#codeProblemn-queen" aria-expanded="false" aria-controls="collapseTwo">
<!-- title -->
<i class="fas fa-caret-right"></i> <p class="title">Code</p>
</div>
<div id="codeProblemn-queen" class="collapse">
```c++
#include <bits/stdc++.h>
using namespace std;
int n;
vector <pair <int, int>> queen;
vector <pair <int, int>> solution;
bool valid (int r, int c) {
for (auto pp: queen) {
// if same row or same column or same diagonal
if ((pp.first == r) or
(pp.second == c) or
(abs(r - pp.first) == abs(c - pp.second))) {
return false;
}
}
return true;
}
void backtrack (int r) {
if (r == n) {
solution = queen;
return;
}
if (!solution.empty()) {
return;
}
for (int c = 0; c < n; c++) {
if (valid(r, c)) {
queen.push_back({r, c});
backtrack(r + 1);
queen.pop_back();
}
}
}
int main () {
cin >> n;
backtrack(0);
if (solution.empty()) {
cout << "NO\n";
return (0);
}
vector <vector <int>> board(n, vector <int> (n, 0));
for (auto pp: solution) {
board[pp.first][pp.second] = 1;
}
cout << "YES\n";
for (int r = 0; r < n; r++) {
for (int c = 0; c < n; c++) {
cout << board[r][c] << " \n"[c == n - 1];
}
}
return (0);
}
```
</div>
<!-- ends code -->
For $N = 4$ the recursion tree of our solution is like this:
<div class="row text-center img-border">
![](./images/class-08/n-queen.png)
Image taken from [Jeff Erickson - Algorithms - Chapter 2: Backtracking](http://jeffe.cs.illinois.edu/teaching/algorithms/).
</div>
The complexity of the above solution comes from the equation:
$$T_n = n \cdot T_{n - 1} + O(n)$$
$$\to T_n = O(n!)$$
Then, our solution has complexity $O(n!)$.
Recommended readings:
* [HackerEarth - Recursion and Backtracking](https://www.hackerearth.com/practice/basic-programming/recursion/recursion-and-backtracking/tutorial/)
* Competitive Programming 3, section 3.2.2, 8.2.1 and 8.2.2.
* [GeekForGeeks - Backtracking Algorithms](https://www.geeksforgeeks.org/backtracking-algorithms/)
<div class="topic" id="contest">Contest</div>
You can find the contest [here](https://vjudge.net/contest/354334).
<!-- Begins problem A -->
<div class="card" id="A">
<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: CD</p>
</div>
<!-- begin body -->
<div id="collapseProblemA" class="collapse">
<div class="card-body solution-body">
### <a href="https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=565" target="_blank">CD</a>
Each element can be taken or not, then a backtracking solution will give us the
answer and keet the initial order of the items.
<!-- 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>
using namespace std;
int main () {
int n;
while (cin >> n) {
int m;
cin >> m;
vector <int> arr(m);
for (int& elem: arr) cin >> elem;
vector <int> take;
vector <int> ans;
int sum = 0;
int best_sum = 0;
function <void(int)> backtrack = [&] (int pos) -> void {
if (sum > best_sum or (sum == best_sum and ans.size() < take.size())) {
best_sum = sum;
ans = take;
}
if (pos == m) return;
// do not take it
backtrack(pos + 1);
if (sum + arr[pos] > n) return;
// take it
take.push_back(arr[pos]);
sum += arr[pos];
backtrack(pos + 1);
take.pop_back();
sum -= arr[pos];
};
backtrack(0);
for (int elem: ans) cout << elem << ' ';
cout << "sum:" << best_sum << '\n';
}
return (0);
}
```
</div>
<!-- ends code -->
</div>
</div>
</div>
<!-- ends problem A -->
<!-- Begins problem B -->
<div class="card" id="B">
<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: Hanoi Tower Troubles Again!</p>
</div>
<!-- begin body -->
<div id="collapseProblemB" class="collapse">
<div class="card-body solution-body">
### <a href="https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1217" target="_blank">Hanoi Tower Troubles Again!</a>
There is a greedy approach, you can put a ball in the first pile where you can
do it.
<!-- 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>
using namespace std;
int main () {
const int N = 1e5;
vector <bool> is_sq(N, false);
for (int i = 0; i * i < N; i++) is_sq[i * i] = true;
int tc;
cin >> tc;
while (tc--) {
int n;
cin >> n;
vector <vector <int>> pile(n);
int ans = 0;
int cur = 0;
function <void(int)> rec = [&] (int num) -> void {
ans = max(ans, cur);
for (int i = 0; i < n; i++) {
if (pile[i].empty() or is_sq[pile[i].back() + num]) {
cur += 1;
pile[i].push_back(num);
rec(num + 1);
break;
}
}
};
rec(1);
cout << ans << '\n';
}
return (0);
}
```
</div>
<!-- ends code -->
</div>
</div>
</div>
<!-- ends problem B -->
<!-- Begins problem C -->
<div class="card" id="C">
<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: Marcus</p>
</div>
<!-- begin body -->
<div id="collapseProblemC" class="collapse">
<div class="card-body solution-body">
### <a href="https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1393" target="_blank">Marcus</a>
Identify the initial point and then search on the grid using backtracking.
<!-- 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>
using namespace std;
int main () {
const vector <int> dr = {-1, 0, 0};
const vector <int> dc = {0, -1, 1};
const vector <string> option = {"forth", "left", "right"};
const string word = "IEHOVA#";
int tc;
cin >> tc;
while (tc--) {
int n, m;
cin >> n >> m;
vector <string> ans;
vector <string> take;
vector <string> grid(n);
for (int i = 0; i < n; i++) cin >> grid[i];
function <void(int,int)> backtrack = [&] (int r, int c) -> void {
if (take.size() == 7) {
ans = take;
return;
}
for (int d = 0; d < 3; d++) {
if (!ans.empty()) return;
int nr = r + dr[d];
int nc = c + dc[d];
if (not (0 <= min(nr, nc) and nr < n and nc < m)) continue;
if (grid[nr][nc] != word[take.size()]) continue;
take.push_back(option[d]);
backtrack(nr, nc);
take.pop_back();
}
};
for (int r = 0; r < n; r++) {
for (int c = 0; c < m; c++) {
if (grid[r][c] == '@') {
backtrack(r, c);
}
}
}
for (int i = 0; i < 7; i++) {
cout << ans[i] << " \n"[i == 6];
}
}
return (0);
}
```
</div>
<!-- ends code -->
</div>
</div>
</div>
<!-- ends problem C -->
<!-- Begins problem D -->
<div class="card" id="D">
<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: Back to the 8-Queens</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=2026" target="_blank">Back to the 8-Queens</a>
There are just 92 valid configurations, we can generate all of them using
backtracking and do a simple linear search to get the answer for each query.
<!-- 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>
using namespace std;
const int N = 8;
vector <pair <int, int>> queen;
vector <vector <pair <int, int>>> solution;
bool valid (int r, int c) {
for (auto pp: queen) {
// if same row or same column or same diagonal
if ((pp.first == r) or
(pp.second == c) or
(abs(r - pp.first) == abs(c - pp.second))) {
return false;
}
}
return true;
}
void backtrack (int c) {
if (c == N + 1) {
solution.push_back(queen);
return;
}
for (int r = 1; r <= N; r++) {
if (valid(r, c)) {
queen.push_back({r, c});
backtrack(c + 1);
queen.pop_back();
}
}
}
int main () {
backtrack(1);
vector <int> row(N);
int tc = 0;
while (cin >> row[0]) {
for (int i = 1; i < N; i++) cin >> row[i];
int ans = INT_MAX;
for (auto sol: solution) {
int need = 0;
for (int i = 0; i < N; i++) {
need += (row[i] != sol[i].first);
}
ans = min(ans, need);
}
cout << "Case " << ++tc << ": " << ans << '\n';
}
return (0);
}
```
</div>