第十四届蓝桥杯_Java_A组_与或异或

本文展示了两个Java代码示例,一个是使用`BinaryOperator`实现AND、OR和XOR操作的组合计数,另一个是深度优先搜索算法在电路分析中的应用。通过递归计算有效组合数和电路中满足特定条件的路径数。

目录

问题描述

参考代码

示例一

示例二


问题描述



参考代码


 示例一


import java.util.function.BinaryOperator;

public class Main {
    // AND、OR和XOR操作的二元操作符
    private static final BinaryOperator<Integer> AND = (x, y) -> x & y;
    private static final BinaryOperator<Integer> OR = (x, y) -> x | y;
    private static final BinaryOperator<Integer> XOR = (x, y) -> x ^ y;
    private static final BinaryOperator<Integer>[] operations = new BinaryOperator[]{AND, OR, XOR};

    // 计算有效组合数的方法
    public static int countValidCombinations(int level, int[] values) {
        // 基本情况:如果我们已经到达最后一级
        if (level == 1) {
            return values[0] == 1 ? 1 : 0;
        }

        int validCombinations = 0;
        // 生成当前级别的所有可能组合
        for (int opIndex = 0; opIndex < Math.pow(3, level - 1); opIndex++) {
            int[] newValues = new int[level - 1];
            int tempIndex = opIndex;

            // 计算当前组合的输出
            for (int i = 0; i < level - 1; i++) {
                int op = tempIndex % 3;
                tempIndex /= 3;
                newValues[i] = operations[op].apply(values[i], values[i + 1]);
            }

            // 递归计算下一级别的组合数
            validCombinations += countValidCombinations(level - 1, newValues);
        }
        return validCombinations;
    }

    public static void main(String[] args) {
        // 初始输入值
        int[] inputValues = {1, 0, 1, 0, 1};
        // 从顶级开始计数
        int result = countValidCombinations(inputValues.length, inputValues);
        // 输出结果
        System.out.println("总的有效组合数:" + result);
    }
}

示例二


public class Main {
    private int[][] circuit = new int[6][6];
    private int answer = 0;
    private final int target = 1;

    public static void main(String[] args) {
        new Main().run();
    }

    private void run() {
        // 初始化电路的基本情况。
        circuit[5] = new int[]{0, 1, 0, 1, 0, 1};
        // 从电路的顶部开始深度优先搜索。
        depthFirstSearch(1, 5);
        // 打印计算出的答案。
        System.out.println(answer);
    }

    private void depthFirstSearch(int index, int level) {
        if (level <= 1) {
            // 基本情况:如果当前单元格与目标匹配,增加答案。
            if (circuit[level][index] == target) {
                answer++;
            }
        } else {
            if (index < level) {
                // 执行与运算并继续搜索。
                circuit[level - 1][index] = circuit[level][index] & circuit[level][index + 1];
                depthFirstSearch(index + 1, level);
                // 执行或运算并继续搜索。
                circuit[level - 1][index] = circuit[level][index] | circuit[level][index + 1];
                depthFirstSearch(index + 1, level);
                // 执行异或运算并继续搜索。
                circuit[level - 1][index] = circuit[level][index] ^ circuit[level][index + 1];
                depthFirstSearch(index + 1, level);
            } else {
                // 移动到电路的下一个深度级别。
                depthFirstSearch(1, level - 1);
            }
        }
    }
}

### 蓝桥杯 异或算法 题目及解答 #### 一、异或和之和 对于给定的一个序列 `[a_1, a_2, ..., a_n]`,我们需要计算所有子区间的异或和的总和。 通过构造前缀和 `S[i]` 表示从第 `1` 到第 `i` 的异或和,则任意区间 `[L, R]` 的异或和可以表示为 `(S[R] ^ S[L-1])`[^1]。 实现此逻辑可以通过遍历整个数并利用前缀和快速获取每段区间的异或值来完成: ```python def xor_sum_of_subarrays(arr): n = len(arr) prefix_xor = [0] * (n + 1) # 构造前缀异或 for i in range(n): prefix_xor[i + 1] = prefix_xor[i] ^ arr[i] total_xor_sum = 0 for L in range(1, n + 1): # 左端点 for R in range(L, n + 1): # 右端点 total_xor_sum += (prefix_xor[R] ^ prefix_xor[L - 1]) return total_xor_sum ``` --- #### 二、异或三角形 在该问题中,目标是从集合 `{a, b, c}` 中找到满足条件的三元 `(a, b, c)` 来构成一个有效的三角形。为了简化枚举过程中的复杂度,我们可以引入约束条件:假设 `c = a ⊕ b` 并验证其是否小于其他两数之和[^4]。 以下是基于上述思路的一种解决方案: ```python from itertools import combinations def count_valid_triangles(nums): nums.sort() valid_count = 0 for a, b in combinations(nums, 2): c = a ^ b if c not in nums or c >= max(a, b): continue if a + b > c and abs(a - b) < c: valid_count += 1 return valid_count ``` --- #### 三、异或和之差 本题的核心在于最大化者最小化两个选定数值之间的异或结果差异。为此,采用一种高效的数据结构——Trie树(字典树),能够帮助我们在 O(log(max_value)) 时间内查询最优解[^3]。 具体步骤如下所示: 1. 计算输入列表的累积异或值; 2. 使用这些累计值得到可能的最大/最小区间异或对; 3. 维护四个辅助数存储左侧右侧各自对应的最大最小值信息;最终迭代更新全局最佳答案即可得出结论。 下面是 Python 实现版本: ```python class TrieNode: def __init__(self): self.children = {} def insert(trie_root, num): node = trie_root for bit in reversed(range(32)): # 假设整型有32位 current_bit = (num >> bit) & 1 if current_bit not in node.children: node.children[current_bit] = TrieNode() node = node.children[current_bit] def query_max(trie_root, num): node = trie_root res = 0 for bit in reversed(range(32)): current_bit = (num >> bit) & 1 opposite_bit = 1 - current_bit if opposite_bit in node.children: res |= (opposite_bit << bit) node = node.children[opposite_bit] elif current_bit in node.children: node = node.children[current_bit] else: break return res ^ num def max_min_xor_difference(nums): n = len(nums) # Step 1: Compute prefix XOR array prefix_xors = [0] * (n + 1) for i in range(n): prefix_xors[i + 1] = prefix_xors[i] ^ nums[i] # Step 2: Build TRIE tree to find maximums/minimals efficiently root = TrieNode() lmax = [float('-inf')] * (n + 1) rmin = [float('inf')] * (n + 1) for idx in range(1, n + 1): insert(root, prefix_xors[idx]) lmax[idx] = max(lmax[idx - 1], query_max(root, prefix_xors[idx])) root = TrieNode() # Reset the trie structure for jdx in range(n, 0, -1): insert(root, prefix_xors[jdx]) rmin[jdx] = min(rmin[jdx + 1], query_max(root, prefix_xors[jdx])) result = float('-inf') for k in range(1, n + 1): candidate = lmax[k] - rmin[k] if candidate > result: result = candidate return result ``` ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值