yohandi
A recent graduate with a strong interest in algorithms and data structures.

CSC3100 Data Structures Fall 2023 Assignment Solutions Writeup

In the very recent term, I got an opportunity to become the teaching assistant for the CSC3100 Data Structures course. The below are compilation of solutions writeup made by me for all the assignments. These solutions are from my own insights and perspectives on the problems and are unofficial. PDF version can be found at the bottom of this page.

Assignment 1

Queue Disorder

Written and developed by: Xuanhao Pan

Editorial by: Yohandi

Description

In a queue, people are supposed to stand in ascending order of their heights. However, due to some confusion, the order of the queue gets disrupted. Your task is to determine the number of disorder pairs in the queue.

A disorder pair is defined as a pair of people

KaTeX can only parse string typed expression
such that
KaTeX can only parse string typed expression
and
KaTeX can only parse string typed expression
is taller than
KaTeX can only parse string typed expression
in the queue, which means their order is reversed.

For example, consider a queue with 5 people:

KaTeX can only parse string typed expression
. In this case, there are 6 disorder pairs:
KaTeX can only parse string typed expression
and
KaTeX can only parse string typed expression
. Please note that
KaTeX can only parse string typed expression
is not considered as a disorder pair. Write a program to calculate the number of disorder pairs in a given queue with
KaTeX can only parse string typed expression
people.

Constraints

  • KaTeX can only parse string typed expression
  • KaTeX can only parse string typed expression

Solution

This problem is a straightforward inversion count problem. We can use merge sort to maintain the number of inversions between pairs. Suppose a range

KaTeX can only parse string typed expression
accounts for the number of inversions of all pairs in the range. This then recurses into sub-ranges
KaTeX can only parse string typed expression
and
KaTeX can only parse string typed expression
. Any indices
KaTeX can only parse string typed expression
and
KaTeX can only parse string typed expression
such that
KaTeX can only parse string typed expression
and
KaTeX can only parse string typed expression
can be processed concurrently with the merge procedure for the two half arrays using the sorted property.

Alternatively, we can use a Binary Indexed Tree to count the number of elements within a specific index range. To count only those elements smaller than a certain number, updates can be made following the sequence of the sorted elements. Each element, however, should be mapped into a pair of itself and its index (descendingly) to handle elements with the same value.

Both solutions work in

KaTeX can only parse string typed expression
.

#include <bits/stdc++.h>
using namespace std;

class BIT {
private:
...

Star Sequence

Written and developed by: Tianci Hou

Editorial by: Yohandi

Description

Renko Usami observes space through a telescope when she notices a fantastic phenomenon – the number of stars in the fields follows a mathematical pattern.

Specifically, let’s denote the number of stars in the

KaTeX can only parse string typed expression
-th field by
KaTeX can only parse string typed expression
, then
KaTeX can only parse string typed expression
satisfies the following expression, and
KaTeX can only parse string typed expression
are given positive integers.

KaTeX can only parse string typed expression

Now Renko Usami is curious about how many stars in the

KaTeX can only parse string typed expression
-th field, but the
KaTeX can only parse string typed expression
-th field is too far away to be observed through her cheap astronomical telescope. Since there are so many stars, she only cares about the value of the number of stars modulo
KaTeX can only parse string typed expression
. In other words, she want to know
KaTeX can only parse string typed expression
.

Fortunately, Renko Usami is able to observe the two closest star fields to her, and the numbers of stars in fields are

KaTeX can only parse string typed expression
and
KaTeX can only parse string typed expression
. Unfortunately, she is going to be late again for her appointment with Merry. Can you write a program for her to calculate
KaTeX can only parse string typed expression
?

Constraints

  • KaTeX can only parse string typed expression
  • KaTeX can only parse string typed expression
  • KaTeX can only parse string typed expression

Solution

To calculate

KaTeX can only parse string typed expression
, we use matrix exponentiation to efficiently compute the required term in the sequence. We can construct a vector consisting of
KaTeX can only parse string typed expression
and
KaTeX can only parse string typed expression
using the following matrix power multiplied by the initial vector, which consists of
KaTeX can only parse string typed expression
and
KaTeX can only parse string typed expression
. The formulation is derived as follows:

KaTeX can only parse string typed expression

The matrix power can be computed using the divide and conquer technique, which works in

KaTeX can only parse string typed expression
.

#include <bits/stdc++.h>
using namespace std;

long long MOD;

...

Assignment 2

Battle Game

Written and developed by: Bingwei Zhang

Editorial by: Yohandi

Description

Imagine a group of

KaTeX can only parse string typed expression
players that are located in different floors. The
KaTeX can only parse string typed expression
-th player (for each
KaTeX can only parse string typed expression
such that
KaTeX can only parse string typed expression
, where
KaTeX can only parse string typed expression
is an integer) is characterized by the following:

  • KaTeX can only parse string typed expression
    , a unique starting floor level
  • KaTeX can only parse string typed expression
    , a starting HP (Health Points) value
  • KaTeX can only parse string typed expression
    , a direction of movement, either U indicating that the
    KaTeX can only parse string typed expression
    -th player is going upward or D indicating that the
    KaTeX can only parse string typed expression
    -th player is going downward

All players move simultaneously at the same speed in their respective directions. When two players meet, they engage in a battle. The player with the lower health is eliminated instantaneously, while the other continue to move in the same direction at the same speed but with a reduced HP by

KaTeX can only parse string typed expression
. In a case where two players have identical HP, they are both eliminated simultaneously after the battle.

Your task is to determine the final HP of the surviving players

Constraints

  • KaTeX can only parse string typed expression
  • KaTeX can only parse string typed expression
  • KaTeX can only parse string typed expression
  • KaTeX can only parse string typed expression
    U, D
    KaTeX can only parse string typed expression

Solution

Note that downward-moving players survive only if they win every battle with all players below them that are moving upward. Moreover, there won't be any fight between players that are moving in the same direction.

To solve this, we first sort the players by their starting floor. We then simulate from the lowest floor. If a player is moving up, we add them to a stack. Otherwise, this player battles against every player in the current state of the stack, starting from the one on top.

#include <algorithm>
#include <cassert>
#include <iostream>
#include <stack>
#include <vector>
...

Personal comment: the overall solution works in

KaTeX can only parse string typed expression
; however, the constant itself was made strict as stack, the main solution, works in
KaTeX can only parse string typed expression
. The sorting algorithm dominates the runtime of the overall algorithm. The constraint of
KaTeX can only parse string typed expression
should have been lower than or equal to
KaTeX can only parse string typed expression
instead of
KaTeX can only parse string typed expression
so that we can use the counting sort algorithm, which can be well-applied in
KaTeX can only parse string typed expression
.

Buried Treasure

Written and developed by: Yohandi

Editorial by: Yohandi

Description

Jack Sparrow, the legendary pirate of the Seven Seas, sets sail to an inhabited island in search of a buried treasure. Guided by his map, he believes the treasure lies within a weird-looking trench. The trench stretches across a width of

KaTeX can only parse string typed expression
. For any given point from
KaTeX can only parse string typed expression
to
KaTeX can only parse string typed expression
on the trench’s
KaTeX can only parse string typed expression
-coordinate, the depth is represented by
KaTeX can only parse string typed expression
(for each
KaTeX can only parse string typed expression
such that
KaTeX can only parse string typed expression
, where
KaTeX can only parse string typed expression
is an integer).

Jack is wondering about the size of the largest treasure that could possibly fit inside the trench. Wanting to maximize his haul, he turns to you, a trusted member of his crew, to make the calculations. By largest, Jack means the maximum area – the product of width and height – of the rectangular treasure chest that can be buried within the trench’s confines. For example, the following figure shows the largest possible treasure that can fit in a trench with

KaTeX can only parse string typed expression
and
KaTeX can only parse string typed expression
.

Figure 1
Figure 1

Could you give these calculations a look for our legendary pirate?

Constraints

  • KaTeX can only parse string typed expression
  • KaTeX can only parse string typed expression
  • KaTeX can only parse string typed expression
  • The sum of
    KaTeX can only parse string typed expression
    over all queries, denoted as
    KaTeX can only parse string typed expression
    , does not exceed
    KaTeX can only parse string typed expression
    in each test case.

Solution

This problem is a classic "Maximum Rectangle Area in Histogram" problem with a rephrased and modified statement. However, the proof of optimal chest rotation angles is only between

KaTeX can only parse string typed expression
is still needed to correctly solve this problem.

The approach is to have a stack that maintains the indices of depths in ascending order so that we can identify the potential of extension (starting points) for rectangles. Each of those rectangles is computed as

KaTeX can only parse string typed expression
, where
KaTeX can only parse string typed expression
is the rightmost index to which the rectangle containing the
KaTeX can only parse string typed expression
-th index can extend (same goes for
KaTeX can only parse string typed expression
but on the other direction). The main task is to find
KaTeX can only parse string typed expression
.

#include <bits/stdc++.h>
using namespace std;

long long largest_chest(int n, vector<int> &v) {
  long long ret = 0;
...

Assignment 3

Node Distance

Written and developed by: Yige Jiang

Editorial by: Yohandi

Description

You are given a tree with

KaTeX can only parse string typed expression
nodes, where each edge in the tree has a corresponding weight denoting the length of each edge. The nodes in the tree are colored either black or white. Your task is to calculate the sum of distances between every pair of black nodes in the tree. Let
KaTeX can only parse string typed expression
a set of black nodes, then the answer is formulated as:

KaTeX can only parse string typed expression

where

KaTeX can only parse string typed expression
denotes the number of the black nodes in the tree, and
KaTeX can only parse string typed expression
is the length of the simple path from the
KaTeX can only parse string typed expression
-th to
KaTeX can only parse string typed expression
-th black node.

Write a program to calculate the formulation above.

Constraints

  • KaTeX can only parse string typed expression
  • KaTeX can only parse string typed expression
  • KaTeX can only parse string typed expression
  • KaTeX can only parse string typed expression

Solution

Suppose we focus on the contribution of each edge to the total distance. An edge connecting nodes

KaTeX can only parse string typed expression
and
KaTeX can only parse string typed expression
, when removed, splits the tree into two subtrees, say they are
KaTeX can only parse string typed expression
and
KaTeX can only parse string typed expression
. The key insight here is that this edge contributes to the total distance exactly the product of the number of black nodes in
KaTeX can only parse string typed expression
and the number of black nodes in
KaTeX can only parse string typed expression
.

The implementation is done by performing a DFS from any fixed root. During DFS, we count the number of black nodes in each subtree. For a subtree rooted at

KaTeX can only parse string typed expression
, the count of black nodes in
KaTeX can only parse string typed expression
is the number of black nodes within this subtree. The count for
KaTeX can only parse string typed expression
is determined by subtracting the count of black nodes in
KaTeX can only parse string typed expression
from the total number of black nodes in the tree.

#include <bits/stdc++.h>
using namespace std;

int main() {
  ios_base::sync_with_stdio(0);
...

Price Sequence

Written and developed by: Ruiying Liu

Editorial by: Yohandi

Description

Mario bought

KaTeX can only parse string typed expression
math books and he recorded their prices. The prices are all integers, and the price sequence is
KaTeX can only parse string typed expression
of length
KaTeX can only parse string typed expression
. Please help him to manage this price sequence. There are three types of operations:

  • BUY x: buy a new book with price
    KaTeX can only parse string typed expression
    , thus
    KaTeX can only parse string typed expression
    is added at the end of
    KaTeX can only parse string typed expression
    .
  • CLOSEST_ADJ_PRICE: output the minimum absolute difference between adjacent prices.
  • CLOSEST_PRICE: output the absolute difference between the two closest prices in the entire sequence.

A total of

KaTeX can only parse string typed expression
operations are performed. Each operation is one of the three mentioned types. You need to write a program to perform given operations. For operations CLOSEST_ADJ_PRICE and CLOSEST_PRICE you need to output the corresponding answers.

Constraints

  • KaTeX can only parse string typed expression
  • KaTeX can only parse string typed expression
  • KaTeX can only parse string typed expression

Solution

Both the CLOSEST_ADJ_PRICE and CLOSEST_PRICE operations are independent to each other; hence, for each update, i.e., the BUY x operation, we can perform a separate update on two different data structures.

  • For the CLOSEST_ADJ_PRICE operation, we maintain two variables: the price of the last book bought and the minimum absolute difference between adjacent prices. When a BUY x operation occurs, update the last book's price to x and, if necessary, update the minimum absolute difference using the absolute difference between x and the previously last book's price.
  • For the CLOSEST_PRICE operation, we use a balanced binary search tree to avoid the linear time complexity in the insertion worst case. Upon inserting a new price x, we compare it with its immediate predecessor and successor in the tree to update the minimum absolute difference between any two prices in the sequence.
#include <bits/stdc++.h>
using namespace std;

int main() {
  ios_base::sync_with_stdio(0);
...

Assignment 4

Divine Ingenuity

Written and developed by: Shu Wang

Editorial by: Yohandi

Description

If you have ever played Genshin Impact, you probably know about the “Divine Ingenuity: Collector’s Chapter” event. In this event, players can create custom domains by arranging components, including props and traps, between the given starting point and exit point.

Paimon does not want to design a difficult domain; she pursues the ultimate “automatic map”. In the given domain with a size of

KaTeX can only parse string typed expression
, she only placed Airflow and Spikes. Specifically, Spikes will eliminate the player (represented by x), while the Airflow will blow the player to the next position according to the wind direction (up, left, down, right represented by w, a, s, d, respectively).

The starting point and exit point are denoted by i and j, respectively. Ideally, in Paimon’s domain, the player selects a direction and advances one position initially; afterward, the Airflow propels the player to the endpoint without falling into the Spikes. The player will achieve automatic clearance in such a domain.

However, Paimon, in her slight oversight, failed to create a domain that allows players to achieve automatic clearance. Please assist Paimon by making the minimum adjustments to her design to achieve automatic clearance.

Given that the positions of the starting point and exit point are fixed, you can only adjust components at other locations. You have the option to remove existing component at any position; then, place a new direction of Airflow, or position a Spikes.

Constraints

  • KaTeX can only parse string typed expression

Solution

This problem can be modeled as a graph problem, where:

  • For nodes corresponding to Airflow, an edge is created to the node in the direction of the Airflow with weight 0, as no adjustment is needed. For nodes in directions other than the Airflow, edges are created to the adjacent nodes in their respective directions with weight 1, indicating that one adjustment (changing the direction of the Airflow) is required.
  • For Spikes nodes are connected to all adjacent nodes with weight 1, as a Spike can be replaced with an Airflow in any direction with one adjustment.

We run Dijkstra's algorithm to find the shortest path from a node with the character i to a node with the character j.

#include "dijkstra.hpp"
#include <bits/stdc++.h>
using namespace std;

int main() {
...

Edge Changing

Written and developed by: Ziyi Zhao

Editorial by: Yohandi

Description

Give you a graph with

KaTeX can only parse string typed expression
vertices and
KaTeX can only parse string typed expression
edges. No two edges connect the same two vertices. For vertex ID from
KaTeX can only parse string typed expression
to
KaTeX can only parse string typed expression
, we do the following operation: If any two neighbors of a vertex have a
KaTeX can only parse string typed expression
relationship in terms of their IDs, we add a new edge between them. In other words, for any vertex
KaTeX can only parse string typed expression
to
KaTeX can only parse string typed expression
, if
KaTeX can only parse string typed expression
or
KaTeX can only parse string typed expression
, we add an edge
KaTeX can only parse string typed expression
, where
KaTeX can only parse string typed expression
. Besides, if there is already an edge between
KaTeX can only parse string typed expression
and
KaTeX can only parse string typed expression
, no operation is taken.

After the operation, we want you to output the BFS order starting from vertex

KaTeX can only parse string typed expression
. Please traverse all neighbors in ascending order of their IDs when expanding a vertex.

Constraints

  • KaTeX can only parse string typed expression
  • KaTeX can only parse string typed expression

Solution

This problem is a straightforward BFS implementation problem with few modifications on the main graph. However, the inserted nodes need to be handled carefully as the problem requires the traversal in ascending order. One of the ways to handle this is to use a balanced binary search tree.

#include <bits/stdc++.h>
using namespace std;

int main() {
  ios_base::sync_with_stdio(0);
...

PDF version