Solutions for the 23rd CJLU ACM Team Contest

Jun 19, 2026

1925 words

10 min read

Algorithm

Contest: The 23rd China Jiliang University ACM Team Contest / ACM Training Final Exam

Date: 2026-06-19

Author: Abs1nthe

Notes

This page is the English version of my solution notes. The difficulty ratings and Codeforces-style ratings are subjective training references, not official contest ratings.

The original Chinese version contains the full reference code blocks. This English version focuses on the problem statements, core observations, algorithms, and complexity analysis so that the structure is easier to read.

Contest Overview

The contest contains 14 problems, labeled A through N. The topics include simulation, elementary number theory, construction, tree DP, shortest paths, disjoint set union, dynamic programming, combinatorial games, and offline processing.

Difficulty and Tags

IDProblemDifficultyCF Ref.TagsNote
ACoin ClassificationMedium-Hard1900Interactive, classification, decision strategyAdaptive interactive problem
BAgent Execution Plan TreeHard2100Tree DP, rerooting, combinatorics, modular inverseCount valid topological orders for each root
CWhy Can Birds FlyEasy900Number theory, gcd, prime factors, enumerationFind the smallest available index
DGTNH?Medium1600Shortest path, Dijkstra, virtual nodesCompress same-color jumps into color nodes
EMatrix ConstructionHard2300Construction, xor permutation, complete mappingThe statement hints that it is not exam-friendly
FWhy Does Life SleepEasy800Simulation, adjacent difference, boundary checkingScan important moments
GACMBTI StringHard2200Construction, subsequence, state compression, searchControl whether 16 patterns appear
HWith This Flame, Cut Through EverythingVery Hard2400Combinatorial game, permutation counting, mathDetermine winner property first, then count optimal permutations
IAll Returns Are EmptyEasy800Divisibility, basic I/OOutput a / b
JAfter the Snow MeltsMedium1700Offline processing, DSU, grid connectivityProcess rising water level by reverse activation
KTaibo’s Hope Beacon DeckMedium-Hard1900Dynamic programming, state optimization, decision processn,m <= 50
LFirst Meeting, A Million TimesSimple1200Prefix sum, construction check, non-negative arrayDetermine whether a valid rearrangement exists
MThen, Toward TomorrowSimple1000Construction, permutation, reverse operation, lexicographic orderCase-based construction
NDice of FateEasy800Simulation, dice state maintenanceMaintain the six faces

A. Coin Classification

Basic Information

  • Time limit: 5000 ms
  • Memory limit: 524288 KB
  • Difficulty: Medium-Hard
  • CF reference rating: 1900
  • Tags: Interactive, classification, decision strategy

Statement Summary

There are n coins divided into three classes A, B, and C. Their weights are strictly increasing by class, and each class has at least one coin. Each query compares two coins. The goal is to determine every coin’s class within at most floor(3n/2) queries. The problem is adaptive and interactive.

Main Idea

Maintain several equality groups. Coins inside one group have already been proven equal by = comparisons, so each group can be represented by one coin.

In the first phase, repeatedly take two representatives and compare them:

  • If they are equal, merge the two groups.
  • If one is lighter, they can be treated as representatives of two different levels.

The key is to use each comparison to reduce uncertainty as much as possible. Equal results merge groups, while unequal results provide order information. After enough representative relations are known, the remaining classes can be assigned by comparing against chosen boundary representatives.

Correctness Sketch

The algorithm only merges coins after an equality comparison, so every equality group is valid. Inequality comparisons are used only to build relative order between representatives. Since the three classes are totally ordered by weight, once a representative is known to be below or above a boundary, all coins in its group receive the corresponding class.

Query Bound

The strategy pairs representatives and tries to make every query either merge two groups or separate two representatives into different categories. With careful bookkeeping, the total number of comparisons can be bounded by floor(3n/2).

B. Agent Execution Plan Tree

Basic Information

  • Difficulty: Hard
  • CF reference rating: 2100
  • Tags: Tree DP, rerooting DP, combinatorics, modular inverse

Statement Summary

Given a tree, choose every node once as the root. For each root, count the number of valid execution orders that respect the parent-before-child dependency in the rooted tree.

Main Idea

For a fixed root, the number of valid orders is a multinomial merge of all child subtrees:

ways[u] = product(ways[v]) * C(size[u] - 1, size[v1], size[v2], ...)

This is the classic count of topological orders of a rooted tree. Precompute factorials and inverse factorials for combination values.

After computing the answer for one root with DFS, rerooting transfers the answer from parent to child. Moving the root across one edge changes which side is considered the child’s subtree. With subtree sizes and modular inverses, the contribution can be updated in O(1) or logarithmic time per edge, depending on implementation.

Complexity

Precomputation is O(n). The two DFS passes are also O(n), so the total complexity is O(n).

C. Why Can Birds Fly

Basic Information

  • Difficulty: Easy
  • CF reference rating: 900
  • Tags: Number theory, gcd, prime factors, enumeration

Statement Summary

Find the smallest valid number/index that satisfies the condition implied by divisibility and common factors.

Main Idea

The condition can be reduced to checking gcd or prime factor relationships. Enumerate candidates from small to large and test whether the candidate is forbidden by the existing factor constraints. The first candidate that passes is the answer.

Complexity

The direct enumeration is small enough for the given limits. With factor extraction, each test is efficient.

D. GTNH?

Basic Information

  • Difficulty: Medium
  • CF reference rating: 1600
  • Tags: Shortest path, Dijkstra, virtual nodes

Statement Summary

There is a graph-like movement system where normal edges and same-color jumps coexist. A naive complete graph over same-color nodes would be too large.

Main Idea

Introduce one virtual node for each color. Moving from an original node to its color node and then from the color node to another original node simulates a same-color jump. This compresses potentially quadratic same-color edges into linear edges.

After building the compressed graph, run Dijkstra.

Complexity

If there are n original nodes, m normal edges, and c colors, the compressed graph has n + c nodes and O(n + m) edges. Dijkstra runs in O((n + m) log(n + c)).

E. Matrix Construction

Basic Information

  • Difficulty: Hard
  • CF reference rating: 2300
  • Tags: Construction, xor permutation, complete mapping

Statement Summary

Construct a matrix or permutation-like object satisfying xor-related constraints.

Main Idea

The key is to interpret the required rows or columns as permutations under xor. A complete mapping is needed: both f(x) and x xor f(x) should behave like permutations over the domain.

When the domain size has the right parity and power-of-two structure, xor operations allow a clean construction. Otherwise, the constraints force collisions and no solution exists.

Complexity

The construction is linear or near-linear in the size of the output.

F. Why Does Life Sleep

Basic Information

  • Difficulty: Easy
  • CF reference rating: 800
  • Tags: Simulation, adjacent differences, boundary check

Statement Summary

Given a sequence of states or moments, determine whether a condition involving adjacent changes can be satisfied.

Main Idea

Only boundary moments and adjacent differences matter. Scan the array once, compare each adjacent pair, and check whether the required change is valid. If any adjacent transition violates the rule, the answer is negative.

Complexity

O(n) time and O(1) extra space.

G. ACMBTI String

Basic Information

  • Difficulty: Hard
  • CF reference rating: 2200
  • Tags: Construction, subsequence, state compression, search

Statement Summary

Construct a string so that the appearance of multiple subsequence patterns matches a target 16-state condition.

Main Idea

Model whether each pattern has appeared as a bitmask. Appending a character updates the mask deterministically. Then the problem becomes a search over states: find a string whose final mask equals the target.

Because there are only 16 relevant pattern states, BFS/DFS over compressed states is practical. A carefully chosen transition order can also make the produced string shorter or more stable.

Complexity

The state space is constant-sized with respect to the pattern mask, so the search is efficient. The output length depends on the construction path.

H. With This Flame, Cut Through Everything

Basic Information

  • Difficulty: Very Hard
  • CF reference rating: 2400
  • Tags: Combinatorial game, permutation counting, math

Statement Summary

Analyze a game or arrangement over permutations, determine the winning property, and count the number of optimal permutations.

Main Idea

First derive the game-theoretic condition. Usually the result depends on parity, fixed positions, or whether a player can force a move into a losing state.

After the winner condition is known, count permutations that satisfy the optimal condition. This part is combinatorial: split positions into independent groups, count arrangements inside each group, and multiply them with factorial or binomial factors under modulo.

Complexity

With precomputed factorials and inverse factorials, counting can be done in linear time over the permutation size.

I. All Returns Are Empty

Basic Information

  • Difficulty: Easy
  • CF reference rating: 800
  • Tags: Divisibility, basic input/output

Statement Summary

Given a and b, output a / b.

Main Idea

This is a direct implementation problem. Read the input, divide, and print the result according to the statement requirements.

J. After the Snow Melts

Basic Information

  • Difficulty: Medium
  • CF reference rating: 1700
  • Tags: Offline processing, DSU, grid connectivity

Statement Summary

Given an elevation grid and several nondecreasing water-level queries, determine whether two cells are connected through cells whose elevation is strictly above the current water level.

Main Idea

A cell is passable under water level w iff:

h > w

As w decreases, more cells become passable. Therefore process queries offline in descending order of water level. Sort all cells by elevation descending. For each query, activate every cell with h > w that has not been activated yet, and union it with activated neighbors.

For each query:

  • If either endpoint is not activated, answer NO.
  • Otherwise, check whether the two endpoints have the same DSU root.

Complexity

Sorting costs O(nm log(nm) + q log q). DSU processing costs O(nm alpha(nm)). Space complexity is O(nm + q).

K. Taibo’s Hope Beacon Deck

Basic Information

  • Difficulty: Medium-Hard
  • CF reference rating: 1900
  • Tags: Dynamic programming, state optimization, decision process

Statement Summary

There are n poison cards and m catalyst cards. Each turn applies poison according to the current poison layers, then one unused card is played, and finally poison damage is triggered multiple times. Determine the maximum total damage over all play orders.

Main Idea

Because n,m <= 50, dynamic programming is feasible.

Let:

dp[i][j][p]

represent the maximum damage after playing i poison cards and j catalyst cards, when the enemy has p poison layers at the beginning of the current turn.

For each state, try playing one poison card or one catalyst card, update the poison layer count and add the damage triggered at the end of the turn. The final answer is the maximum over all states after all cards are played.

Complexity

The number of states is roughly O(n * m * lim), where lim is the maximum possible poison-layer accumulation. Each transition is O(1).

L. First Meeting, A Million Times

Basic Information

  • Difficulty: Simple
  • CF reference rating: 1200
  • Tags: Prefix sum, construction check, non-negative array

Statement Summary

Given a non-negative array a and a target sum S, determine whether the array can be rearranged so that for every position R, there exists some L <= R with subarray sum S.

Main Idea

If S = 0, every valid subarray must consist only of zeros, so every element must be zero.

For S > 0, any element that is neither 0 nor S creates a problem because all numbers are non-negative. It cannot form a sum S alone, and extending left only increases the sum.

Therefore the necessary and sufficient condition is:

  1. Every element is either 0 or S.
  2. At least one element equals S.

Then arrange the array so that every position can look back to the nearest previous S; zeros between them do not change the sum.

Complexity

O(n) time and O(1) or O(n) space depending on implementation.

M. Then, Toward Tomorrow

Basic Information

  • Difficulty: Simple
  • CF reference rating: 1000
  • Tags: Construction, permutation, inverse operation, lexicographic order

Statement Summary

Construct the lexicographically largest initial permutation that becomes 1,2,...,N after exactly M operations. One operation chooses a non-last element and moves it to the end.

Main Idea

For small cases:

  • If n = 1, only 1 is possible.
  • If n = 2, parity of m determines whether the answer is 1 2 or 2 1.

For n >= 3:

  • If m < n - 1, put the largest m values at the front in descending order, then append the remaining values in increasing order.
  • If m >= n - 1, the full descending permutation is lexicographically largest, and extra operations can be consumed by cycling moves.

Complexity

O(n) time and O(n) space.

N. Dice of Fate

Basic Information

  • Difficulty: Easy
  • CF reference rating: 800
  • Tags: Simulation, dice state maintenance

Statement Summary

A standard die starts with top/front/right equal to 1,2,3. Given a sequence of L/R/F/B operations, simulate the die and output the final top face.

Main Idea

Maintain six variables:

top, bottom, front, back, left, right

For each command, update the four affected faces:

  • L: rolling left makes the right face become top.
  • R: rolling right makes the left face become top.
  • F: rolling forward makes the back face become top.
  • B: rolling backward makes the front face become top.

After all operations, output top.

Complexity

O(n) time and O(1) space.

Solutions for the 23rd CJLU ACM Team Contest
Published on
Jun 19, 2026

Enter keywords to start searching