HUD 5323 Solve this interesting problem dfs剪枝搜索,重构线段树

本文介绍了一个有趣的算法问题:如何找到一个最小的非负整数n,使得存在一个根节点范围为[0,n]的线段树能够完全覆盖给定的[L,R]区间。通过递归地搜索所有可能的子区间来解决这个问题,并实现了一个高效的C++程序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Solve this interesting problem


Problem Description
Have you learned something about segment tree? If not, don’t worry, I will explain it for you.
Segment Tree is a kind of binary tree, it can be defined as this:
- For each node u in Segment Tree, u has two values: Lu and Ru.
- If Lu=Ru, u is a leaf node. 
- If LuRu, u has two children x and y,with Lx=Lu,Rx=Lu+Ru2,Ly=Lu+Ru2+1,Ry=Ru.
Here is an example of segment tree to do range query of sum.



Given two integers L and R, Your task is to find the minimum non-negative n satisfy that: A Segment Tree with root node's value Lroot=0 and Rroot=n contains a node u with Lu=L and Ru=R.
 

Input
The input consists of several test cases. 
Each test case contains two integers L and R, as described above.
0LR109
LRL+12015
 

Output
For each test, output one line contains one integer. If there is no such n, just output -1.
 

Sample Input
6 7 10 13 10 11
 

Sample Output
7 -1 12

/*
 * 给定一个区间的 L R 问知否存在这样的线段树 [0 , n] 使得n最小并且包含区间 [L, R]
 * dfs向上搜索, 由于该区间可能是父节点的左儿子或右儿子,分类讨论,注意取整时可能
 * 导致求得的L 或 R 与实际相差1 , 将这四种情况都考虑即可。
 * 注意剪枝, 在线段树中,每个节点的左儿子区间 = 右儿子区间 或者 右儿子加一
 */
 
#include <bits/stdc++.h>
#define endl "\n"
using namespace std;
typedef long long ll;

ll ans = -1;

void dfs(ll l, ll r) {
    if(l == 0) {
        if(ans == -1) {
            ans = r;
        }
        else {
            ans = min(ans, r);
        }
        return ;
    }
    if(l < 0) return ;
    if(ans != -1 && r >= ans) return ;
    if(l < r-l+1) return; // 剪枝
    dfs(l, 2*r - l);
    dfs(l, 2*r - l + 1);
    dfs(2*l - r - 1, r);
    dfs(2*l - r - 2, r);
}

int main() {
    ios::sync_with_stdio(false);
    ll l, r;
    while(cin >> l >> r) {
        if(l == r) {
            cout << l << endl;
            continue;
        }
        ans = -1;
        dfs(l, r);
        cout << ans << endl;
    }
    return 0;
}



### 关于DFS剪枝在蓝桥杯竞赛中的应用 #### 什么是DFS剪枝? 深度优先搜索(Depth-First Search, DFS)是一种常见的遍历或搜索树或图的算法。然而,在实际问题中,由于状态空间可能非常庞大,单纯的DFS可能会导致时间复杂度过高甚至超时。因此,引入了剪枝技术来减少不必要的计算。通过提前判断某些分支不可能达到最优解并将其舍弃,从而显著提升效率。 #### 剪枝的应用场景 在蓝桥杯竞赛中,DFS常用于解决组合、排列、路径规划等问题。而剪枝则可以通过以下方式实现优化: 1. **可行性剪枝**:当当前状态下已经无法满足题目条件时,立即停止继续探索该分支。 2. **最优性剪枝**:对于寻找最小值或最大值的问题,如果发现某个分支的结果无论如何都不会优于已知的最佳结果,则可以直接跳过此分支。 --- #### 示例代码分析 以下是基于蓝桥杯常见题型的一个典型DFS剪枝实例: ##### 数独游戏 数独是一个经典的约束满足问题,适合用DFS求解。为了加速搜索过程,可以在每次放置数字前先验证其合法性,并利用一些启发式策略进一步缩小搜索范围。 ```java public class SudokuSolver { private final int[][] board; public SudokuSolver(int[][] initialBoard) { this.board = initialBoard; } public boolean solve() { return dfs(0); } private boolean dfs(int pos) { if (pos >= 81) return true; // 如果填满了整个棋盘,返回成功 int row = pos / 9, col = pos % 9; if (board[row][col] != 0) return dfs(pos + 1); // 当前位置已有预设值,跳过 for (int num = 1; num <= 9; ++num) { if (isValid(row, col, num)) { // 判断当前位置是否合法 board[row][col] = num; // 尝试填充数字 if (dfs(pos + 1)) return true; // 继续递归尝试下一格 board[row][col] = 0; // 回溯操作 } } return false; // 所有候选数字均失败,回退至上一层级 } private boolean isValid(int r, int c, int n) { for (int i = 0; i < 9; ++i) { if (board[r][i] == n || board[i][c] == n) return false; // 行列冲突检测 } int startRow = 3 * (r / 3), startCol = 3 * (c / 3); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { if (board[startRow + i][startCol + j] == n) return false; // 子网格冲突检测 } } return true; } } ``` 上述代码实现了基本的数独求解器,并加入了简单的剪枝逻辑以排除非法的状态转移[^1]。 --- ##### 权重分配问题 另一个典型的例子来自砝码称重问题。假设给定若干不同重量的砝码以及目标总质量M,问是否存在一种方案使得这些砝码能够恰好组成指定的质量。此类问题可通过DFS枚举所有可能性,同时加入合理的剪枝条件降低冗余运算量。 ```cpp #include <bits/stdc++.h> using namespace std; bool canWeigh(vector<int>& weights, int targetWeight, int index, int currentSum) { if (currentSum == targetWeight) return true; // 达到目标即终止 if (index >= weights.size()) return false; // 超出数组边界也结束 bool result = false; // 不选当前砝码的情况 result |= canWeigh(weights, targetWeight, index + 1, currentSum); // 只有当不会超过上限才考虑选用当前砝码 if (currentSum + weights[index] <= targetWeight && !result) { result |= canWeigh(weights, targetWeight, index + 1, currentSum + weights[index]); } return result; } int main(){ vector<int> wts{1, 2, 4}; cout << (canWeigh(wts, 7, 0, 0)? "Yes": "No") << endl; return 0; } ``` 在此程序片段里,我们不仅限定了递归层数还设置了额外限制防止无意义扩展[^2]。 --- ##### Python版路径之谜 最后来看一道涉及方向控制与重复访问规避的任务。“路径之谜”要求模拟一位骑士按照特定规则穿越迷宫的过程。这里采用广度优先搜索配合记忆化存储机制完成任务。 ```python def find_path(north_arrows, west_arrows): from collections import deque visited = [[False]*len(north_arrows[0]) for _ in range(len(north_arrows))] queue = deque([(0, 0)]) # 初始化起点坐标 while queue: x, y = queue.popleft() if not (0<=x<len(north_arrows) and 0<=y<len(north_arrows[0])) or visited[x][y]: continue visited[x][y]=True north_count=north_arrows[x][y]-sum([visited[k][y]for k in range(x)]) west_count=west_arrows[x][y]-sum([visited[x][l]for l in range(y)]) if abs(north_count)+abs(west_count)>0: possible_moves=[(-north_count<0),(west_count<0)] if any(possible_moves):queue.extend(((x+(not p)*p,y+p*p)for p in possible_moves)) return 'Possible'if all(all(rw)for rw in visited[:-1]):else:'Impossible' ``` 这段脚本展示了如何借助队列结构逐步展开潜在轨迹直至找到符合条件的一条为止[^4]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值