•
6 min read

CSES problem set - Part 1

Table of Contents

Recently I’ve discovered the CSES problem set and I set myself a goal to solve all the problems in order to improve my algorithm skills. To make it even more challenging and to hold myself accountable, I’ve also decided to write about the solutions on my blog.

In this series I will present these solutions. I’m not going to go in order, instead I will present 5 problems per article, which I will pick somehow randomly from the different topics. The language I chose for solving these problems is C++, because the CSES website gives the same amount of time limit for your code to run, regardless of what language to choose. I quickly noticed that the 1 second limit will not be enough in some cases if the code is written in Python, which I initially wanted to use. The articles will include code examples, but if you want the full source code for the solutions, feel free to visit my Github account. Enjoy!

Weird algorithm

Let’s start with the easiest problem of the set. Given a number n, our task is to simulate the following algorithm: if n is even, divide it by 2, otherwise multiply it by 3 and add 1, until n becomes 1. The only question that might arise here is, are there any cases where this algorithm wouldn’t finish, i.e. n would never become 1? The Collatz conjecture says there are no such numbers, so the only thing we have to do is implement the algorithm and print n after every step. Voilà, our first task is done!

while (n != 1) {
	cout << n << ' ';
	if (n % 2) {
		n = n / 2;
	} else {
		n = n * 3 + 1;
	}
}

cout << 1 << endl;

Repetitions

Our task in this problem is to find the longest sequence in a given string, containing the same character. To do this, we are going to iterate through the characters of the string, count the length of the current sequence with repeating characters and check if the length is the best we’ve seen so far. For this, we need to remember the latest character we’ve visited, so in each iteration we can check if the current character is the same (in which case we increment the counter) or different (in which case we reset the counter to 1). Here is what the code looks like:

char current = n[0];
long current_length = 1;
long best = 1;
for (long i = 1; i < n.size(); i++) {
  if (n[i] == current) {
    current_length += 1;
  } else {
    current_length = 1;
  }

  current = n[i];
  best = max(best, current_length);
}

Counting rooms

This is the first problem related to graphs in the set. Essentially, what we need to find is the number of connected components in a graph. In order to do this, our algorithm will be this: we are going to scan through the whole map, and every time we encounter a point which belongs to a room and we haven’t visited it yet, we are going to explore the whole room, by doing a breadth-first search (BFS). Each time we finish a search, we increment a counter (which will be the solution of the problem) and move on to the next unvisited point belonging to a room.

vector<int> neighbor_x = {0, 0, -1, 1};
vector<int> neighbor_y = {1, -1, 0, 0};

// ...
// initialize `terrain` and `visited` 2D vectors based on the input
// ...

int result = 0;
for (int i = 0; i < n; i++) {
  for (int j = 0; j < m; j++) {
    if (terrain[i][j] == 0 && !visited[i][j]) {
      // this point belongs to room we haven't visited yet
      point p = {i, j};
      q.push(p);
      visited[i][j] = true;

      while (q.size() > 0) {
        point visiting = q.front();
        q.pop();
        for (int k = 0; k < 4; k++) { // check all the neighboring points
          int n_x = visiting.x + neighbor_x[k];
          int n_y = visiting.y + neighbor_y[k];
          if (n_x >= 0 && n_x < n && n_y >= 0 && n_y < m
            && !visited[n_x][n_y]) {
            // visiting a new point which belongs to the room
            visited[n_x][n_y] = true;
            point to_visit = {n_x, n_y};
            q.push(to_visit);
          }
        }
      }

      // finished visiting the room, increment the counter
      result += 1;
    }
  }
}

Labyrinth

In this problem we need to find the shortest path between two given points A and B, and then print the directions we need to follow from A to reach B if the path exists, or “NO” otherwise. To be able to find the shortest path, we need to use BFS, as DFS might not find the shortest path between A and B if there are multiple possible paths. So far so good, we know how to find the shortest path, but how to transform this path into a list of directions? For this, we need to store the “parent” node of each node: once we visit a new node, we will consider its parent the node we are coming from. The easiest way to store this information is by using a 2D array, similar to the map. Each cell of the array will contain the coordinates of its parent. Once we arrive at point B during our search, we can use the parent info to go back to the starting point, and at each step we can determine whether it was a right, left, up, or down move by comparing the coordinate of the current node and its parent’s. Let’s see what the code looks like.

The code to implement BFS is basically the same as in the “Counting rooms” problems, with one small difference: when visiting a point, we mark it as its neighbors’ parent point.

if (n_x >= 0 && n_x < n && n_y >= 0 && n_y < m
  && !visited[n_x][n_y]) {
  visited[n_x][n_y] = true;
  parent[n_x][n_y] = visiting;
  point to_visit = {n_x, n_y};
  q.push(to_visit);
}

Once we finish the search and we find the point we were looking for, we use the parent array to track our way back to the starting point.

point current = end;
vector<char> path;
while (current != start) {
  point next = parent[current.x][current.y];
  point diff = {current.x - next.x, current.y - next.y};

  if (diff == point{1, 0}) {
    path.push_back('D');
  } else if (diff == point{-1, 0}) {
    path.push_back('U');
  } else if (diff == point{0, 1}) {
    path.push_back('R');
  } else if (diff == point{0, -1}) {
    path.push_back('L');
  }
  current = next;
}

Dice combinations

Our goal in this problem is to find out the number of combinations a certain number n can be obtained by throwing a dice and summing up the resulting numbers. Let’s find out how this number can be calculated by thinking first about some simple cases.

How many ways are there to obtain 1? Of course, only one, by throwing the dice only once and getting 1. What about 2? We can throw a 2, or two times 1, so the answer is 2. How about 3? Let’s imagine we throw 1 in our first attempt. Now we need 2 more points to reach 3 - but hey, we already know how many ways there are to throw a 2, from our previous step. Similarly, if we throw 2 in our first attempt, we need one more point, and we also know how to achieve that. And of course we can also throw a 3, so our answer is 2 (number of ways to throw a 2, after throwing 1) + 1 (number of ways to throw 1) + 1 (throw 3 directly) = 4.

At this point we know that we can build our solution by looking at the results of some sub-problems. But which sub-problems exactly? Let’s see another example: how many ways there are to throw 8? What we know is that the first throw will give us a number between 1 and 6. This means the remaining score we need to achieve to get 8 will be between 7 and 2, and the number of combinations will be the sum of these. We could calculate the results of our sub-problems recursively, but we can also go in an iterative way: starting from 1, calculate the number of possibilities for all numbers up to n. We can see that this algorithm has O(n) complexity, as for each number from 1 to n, we need to find the sum of the six sub-problems after throwing the dice once. Of course this would be much more complicated if a dice had thousands of sides, as the complexity would become O(n * number_of_sides), but luckily our dice has only 6 faces, so our algorithm is good enough.

One thing we need to be careful about is that numbers between 1 and 6 can be thrown directly, so it’s not enough to sum the results of the sub-problems, but we need to add 1 to it. Let’s see how this can be done in a simple way:

int combinations[n+1];
combinations[0] = 1;

for (int i = 1; i < n+1; i++) {
	long s = 0;
	for (int j = 1; j < min(i, 6) + 1; j++) {
		s += combinations[i-j];
	}
	combinations[i] = s % MOD;
}

The trick is to assign 1 to the first element of the array, and calculate the sum of the previous numbers or the last 6 numbers, whichever number is lower. This way, if the number we are interested in is lower or equal than 6, we add an extra 1. This is much easier than writing conditions to check if we need to add an extra 1 or not.