Table of Contents
SubsetsResourcesSolution - Apple DivisionGenerating Subsets RecursivelyGenerating Subsets with BitmasksPermutationsLexicographical OrderSolution - Creating Strings IGenerating Permutations RecursivelyGenerating Permutations Using next_permutationBacktrackingResourcesSolution - Chessboard & QueensUsing next_permutationUsing BacktrackingPruningProblemsEdit on GithubComplete Search with Recursion
Authors: Darren Yao, Sam Zhang, Michael Cao, Andrew Wang, Benjamin Qi, Dong Liu
Prerequisites
Includes generating subsets and permutations.
Table of Contents
SubsetsResourcesSolution - Apple DivisionGenerating Subsets RecursivelyGenerating Subsets with BitmasksPermutationsLexicographical OrderSolution - Creating Strings IGenerating Permutations RecursivelyGenerating Permutations Using next_permutationBacktrackingResourcesSolution - Chessboard & QueensUsing next_permutationUsing BacktrackingPruningProblemsEdit on Github
Warning!
Although knowledge of recursion is not strictly necessary for Bronze, we think that it makes more sense to include this module as part of Bronze rather than Silver.
Subsets
Focus Problem – read through this problem before continuing!
Resources
Resources | |||
---|---|---|---|
CPH | good explanation + code, no need to repeat |
Solution - Apple Division
Since , we can solve the focus problem by trying all possible divisions of apples into two sets and finding the one with the minimum difference in weights. Here are two ways to do this.
Generating Subsets Recursively
The first method would be to write a recursive function which searches over all possibilities.
At some index, we either add to the first set or the second set, storing two sums and with the sum of values in each set.
Then, we return the difference between the two sums once we've reached the end of the array.
C++
1#include <bits/stdc++.h>2using namespace std;3using ll = long long;4using vi = vector<int>;5#define pb push_back6#define rsz resize7#define all(x) begin(x), end(x)8#define sz(x) (int)(x).size()9using pi = pair<int,int>;10#define f first
Java
1import java.util.*;2import java.io.*;34public class Main {56 static int N;7 static int weights[];89 public static void main(String[] args) throws Exception {10 FastIO sc = new FastIO(System.in); //See "Intro - FastIO" - this class acts similarly to Scanner, but faster
Python
1n = int(input())2p = list(map(int, input().split()))34def solve(i, s1, s2):5 if i == n:6 return abs(s2-s1)7 return min(solve(i+1, s1+p[i], s2),8 solve(i+1, s1, s2+p[i]))910print(solve(0, 0, 0))
Generating Subsets with Bitmasks
Warning!
You are not expected to know this for Bronze.
A bitmask is an integer whose binary representation is used to represent a subset. For a particular bitmask, if the 'th bit is turned on (equal to ), we say the 'th apple is in . Then, the rest of the apples are in . We can iterate through all subsets if we check all bitmasks ranging from to . For each bitmask, find the sum of and and find the minimum difference between their sums.
Note the fancy bitwise operations:
1 << x
for an integer is another way of writing , which, in binary, has only the 'th bit turned on.- The
&
(and) operator will take two integers and return a new integer.a & b
for integers and will return a new integer whose 'th bit is turned on if and only if the 'th bit is turned on for both and . Thus,mask & (1 << x)
will return a positive value only if the 'th bit is turned on in .
Bitwise Operations
Check the Silver module module for more information.
C++
1#include <bits/stdc++.h>2using namespace std;3using ll = long long;4using vi = vector<int>;5#define pb push_back6#define rsz resize7#define all(x) begin(x), end(x)8#define sz(x) (int)(x).size()9using pi = pair<int,int>;10#define f first
Java
1import java.util.*;2import java.io.*;34public class Main {5 public static void main(String[] args) throws Exception {6 FastIO sc = new FastIO(System.in); //see "Intro - FastIO" - this class acts similarly to Scanner7 PrintWriter pw = new PrintWriter(System.out);89 int N = sc.nextInt();10 int weights[] = new int[N];
Python
1n = int(input())2p = list(map(int, input().split()))34ans = float('inf')5for mask in range(1<<n):6 s1,s2 = 0,07 for i in range(n):8 if mask & (1<<i):9 s1 += p[i]10 else:
Permutations
A permutation is a reordering of a list of elements.
Focus Problem – read through this problem before continuing!
Lexicographical Order
This term is mentioned quite frequently, ex. in USACO Bronze - Photoshoot.
Think about how are words ordered in a dictionary. (In fact, this is where the term "lexicographical" comes from.)
In dictionaries, you will see that words beginning with the letter a
appears at the very beginning, followed by words beginning with b
, and so on. If two words have the same starting letter, the second letter is used to compare them; if both the first and second letters are the same, then use the third letter to compare them, and so on until we either reach a letter that is different, or we reach the end of some word (in this case, the shorter word goes first).
Permutations can be placed into lexicographical order in almost the same way. We first group permutations by their first element; if the first element of two permutations are equal, then we compare them by the second element; if the second element is also equal, then we compare by the third element, and so on.
For example, the permutations of 3 elements, in lexicographical order, are
Notice that the list starts with permutations beginning with 1 (just like a dictionary that starts with words beginning with a
), followed by those beginning with 2 and those beginning with 3. Within the same starting element, the second element is used to make comparisions.
Generally, unless you are specifically asked to find the lexicographically smallest/largest solution, you do not need to worry about whether permutations are being generated in lexicographical order. However, the idea of lexicographical order does appear quite often in programming contest problems, and in a variety of contexts, so it is strongly recommended that you familiarize yourself with its definition.
Some problems will ask for an ordering of elements that satisfies certain conditions. In these problems, if , we can just iterate through all permutations and check each permutation for validity.
Solution - Creating Strings I
Resources | |||
---|---|---|---|
CPH | brief explanation + code for both of the methods below |
Generating Permutations Recursively
Just a slight modification of method 1 from CPH.
C++
1int N, cnt[26];2str S, perm;3vs perms;45void search() {6 if (sz(perm) == sz(S)) {7 perms.pb(perm);8 return;9 }10 F0R(i,26) if (cnt[i]) {
Java
1import java.util.*;2import java.io.*;34public class Main {5 static String s, perm;6 static ArrayList<String> perms;7 static int N, cnt[];89 static void search() {10 if (perm.length() == s.length()) {
Generating Permutations Using next_permutation
Resources | |||
---|---|---|---|
Mark Nelson | explanation with an example |
Alternatively, we can just use the next_permutation()
function. This function takes in a range and modifies it to the next greater permutation. If there is no greater permutation, it returns false. To iterate through all permutations, place it inside a do-while
loop. We are using a do-while
loop here instead of a typical while
loop because a while
loop would modify the smallest permutation before we got a chance to process it.
What's going to be in the check
function depends on the problem, but it should verify whether the current permutation satisfies the constraints given in the problem.
1do {2 check(v); // process or check the current permutation for validity3} while(next_permutation(v.begin(), v.end()));
Each call to next_permutation
makes a constant number of swaps on average if we go through all permutations of size .
Warning!
One small detail is that you need to sort the string before calling next_permutation()
because the method generates strings in lexicographical order. If the string isn't sorted, then strings which are lexicographically smaller than the initial string won't be generated.
C++
1#include <bits/stdc++.h>2using namespace std;3using ll = long long;4using vi = vector<int>;5#define pb push_back6#define rsz resize7#define all(x) begin(x), end(x)8#define sz(x) (int)(x).size()9using pi = pair<int,int>;10#define f first
Java
Warning!
next_permutation
is not available in Java.
Backtracking
Focus Problem – read through this problem before continuing!
Resources
Resources | |||
---|---|---|---|
CPH | code and explanation for focus problem | ||
CP2 | iterative vs recursive complete search |
Solution - Chessboard & Queens
Using next_permutation
Since no two queens can be in the same column, let's generate a permutation of length . Then, the represents the column that the -th queen goes on.
By generating all permutations, we can quickly test all possible placements, and count how many are valid.
To make the implementation easier, we can observe that some bottom-left to top-right diagonal can be represented as all squares such that for some . Similarly, some bottom-right to top-left diagonal can be represented as if are zero-indexed.
C++
1#include <bits/stdc++.h>2using namespace std;3using ll = long long;4using vi = vector<int>;5#define pb push_back6#define rsz resize7#define all(x) begin(x), end(x)8#define sz(x) (int)(x).size()9using pi = pair<int,int>;10#define f first
Java
1import java.io.*;2import java.util.*;34public class Chessboard {5 public static boolean ok[][] = new boolean[8][8];6 public static ArrayList < Integer > perm = new ArrayList < Integer > ();7 public static boolean[] chosen = new boolean[8];8 public static int ans = 0;9 public static void main(String[] args) throws IOException {10 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Using Backtracking
According to CPH:
A backtracking algorithm begins with an empty solution and extends the solution step by step. The search recursively goes through all different ways how a solution can be constructed.
Since the bounds are small, we can recursively backtrack over all ways to place the queens, storing the current state of the board.
Then, we can try to place a queen at all squares if it isn't attacked by a queen or blocked and recurse, before removing this queen and backtracking.
Finally, when we have placed all the queens and the board's state is valid, then increment the answer.
C++
1string g[8];2bool sum[15], dif[15], c[8];3int ans = 0;45void dfs(int r) { // place queen in r-th row6 if (r == 8) {7 ++ ans; // found valid placement8 return;9 }10 F0R(i,8) if (g[r][i] == '.' && !c[i] && !sum[i+r] && !dif[i-r+7]) {
Java
1import java.util.*;2import java.io.*;34public class Main {5 static String g[];6 static boolean sum[], dif[], c[];7 static int ans = 0;8 static void dfs(int r) { //place queen in row r9 if (r == 8) {10 ++ ans;
Pruning
Focus Problem – read through this problem before continuing!
Both of the resources below describe this well so I won't repeat it here.
Resources | |||
---|---|---|---|
CPH | code and explanation for focus problem | ||
CP2 | pruning tips |
Problems
None of these require pruning.
Status | Source | Problem Name | Difficulty | Tags | Solution | URL |
---|---|---|---|---|---|---|
Bronze | Hard | Show Tagspermutations | External Sol | |||
Bronze | Hard | |||||
Old Bronze | Very Hard | Show Tagspermutations | External Sol |
You can find more problems at the CP2 link given above or at USACO Training. However, these sorts of problems appear much less frequently then they once did.
This section is not complete.
make code consistent, improve some of these explanations
Module Progress:
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!