DFS (Search)
Introduction
DFS is a concept in graph theory; for details, refer to the DFS (Graph Theory) page. In the context of search algorithms, this term often refers to algorithms that conveniently implement brute-force enumeration using recursive functions. It shares some similarities with the DFS algorithm in graph theory but is not entirely the same.
Explanation
Consider this example:
Example Problem
Decompose the positive integer \(n\) into three positive integers, such as \(6=1+2+3\), where each subsequent number must be greater than or equal to the previous one. Output all possible decompositions.
For this problem, if you are not familiar with search algorithms, what would you do? Naturally, you would use three nested loops, as shown in the reference code below:
Implementation
1 2 3 4 | |
1 2 3 4 5 | |
1 2 3 4 5 6 7 | |
But what if we need to decompose it into four integers? Add another loop? And what about decomposing it into at most \(m\) integers?
This is where recursive search comes into play. The characteristic of such search algorithms is that they divide the search target into several "layers," where each layer makes decisions based on the states of previous layers until the target state is reached.
Consider the problem above: decompose the positive integer \(n\) into at most \(m\) positive integers, where each subsequent number must be greater than or equal to the previous one, and output all possible decompositions.
Suppose a decomposition splits the positive integer \(n\) into \(k\) positive integers \(a_1, a_2, \ldots, a_k\). The problem is divided into layers, where the \(i\)-th layer determines \(a_i\). To make the decision for the \(i\)-th layer, we need to record three state variables: \(n-\sum_{j=1}^i{a_j}\), representing the sum of all remaining positive integers; \(a_{i-1}\), representing the positive integer from the previous layer to ensure the numbers are non-decreasing; and \(i\), ensuring we output at most \(m\) positive integers. To record the decomposition, we use an array arr, where the \(i\)-th element represents \(a_i\). Note that arr is essentially a stack of length \(i\).
The code is as follows:
Implementation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
Example Problems
Luogu P1706 Full Permutation Problem
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 | |
本页面最近更新:,更新历史
发现错误?想一起完善? 在 GitHub 上编辑此页!
本页面贡献者:OI-wiki
本页面的全部内容在 CC BY-SA 4.0 和 SATA 协议之条款下提供,附加条款亦可能应用