跳到正文

题解

题解:P2273 [HNOI2002] 交换

原文
文章信息与版本

文章信息

收录
2026年3月1日
更新
2026年3月1日
篇幅
约 6 分钟
题目
P2273

版本

  1. v1当前

解题思路 首先,分析给定的 CE - 程序对寄存器值的影响。对于每个指令 CE(a, b),如果 ra 中的值大于 rb 中的值,则交换两个寄存器的值。 接着,考虑如何判断一个 CE - 程序是否为可靠的 MIN - 程序。可以通过模拟执行 CE - 程序,并检查在执行完程序后 r1 是否为所有寄存器中的最小值。如果删除任意一条指令后 r1 不再是最小值,那么该程序不是可靠的 MIN - 程序。 为了使给定的 CE - 程序成为可靠的 MIN - 程序,可以遍历所有可能的指令组合,添加到程序的尾部,并检查是否满足可靠的 MIN - 程序的条件。找到满足条件所需添加的最少指令数量。 C++ 代码实现 #include <iostream> #include <vector> // 模拟比较交换指令 void compareAndExchange(int& a, int& b) { if (a > b) { int temp = a; a = b; b = temp; } } // 判断给定的 CE 程序是否为可靠的 MIN 程序 bool isReliableMINProgram(const vector<pair<int, int>>& program, int n) { vector<int> registers(n); // 初始化寄存器的值 for (int i = 0; i < n; ++i) { registers[i] = i + 1; } // 执行 CE 程序 for (const auto& instruction : program) { compareAndExchange(registers[instruction.first - 1], registers[instruction.second - 1]); } // 检查 r1 是否为最小值 int minValue = registers[0]; for (int value : registers) { if (value < minValue) { return false; } } // 逐个删除指令检查是否仍然是 MIN 程序 for (int i = 0; i < program.size(); ++i) { std::vector<int> tempRegisters = registers; std::vector<std::pair<int, int>> tempProgram = program; tempProgram.erase(tempProgram.begin() + i); for (int j = 0; j < n; ++j) { tempRegisters[j] = j + 1; } for (const auto& instruction : tempProgram) { compareAndExchange(tempRegisters[instruction.first - 1], tempRegisters[instruction.second - 1]); } minValue = tempRegisters[0]; for (int value : tempRegisters) { if (value < minValue) { return false; } } } return true; }

// 找到使给定程序成为可靠的 MIN 程序所需添加的最少指令数量 int findMinInstructionsToMakeReliable(const std::vector<std::pair<int, int>>& originalProgram, int n) { int addedInstructions = 0; std::vector<std::pair<int, int>> currentProgram = originalProgram; while (!isReliableMINProgram(currentProgram, n)) { for (int i = 1; i <= n; ++i) { for (int j = i + 1; j <= n; ++j) { currentProgram.push_back({i, j}); if (isReliableMINProgram(currentProgram, n)) { return addedInstructions; } currentProgram.pop_back(); } } addedInstructions++; } return addedInstructions; } 你可以使用以下方式调用这个函数: cpp 复制 int main() { std::vector<std::pair<int, int>> program = {{1, 2}, {2, 3}, {1, 2}}; int n = 3; int result = findMinInstructionsToMakeReliable(program, n); std::cout << result << std::endl; return 0; } 这段代码首先实现了比较交换函数 compareAndExchange,用于模拟比较交换指令的执行。然后,定义了函数 isReliableMINProgram 来判断给定的 CE 程序是否为可靠的 MIN 程序。最后,函数 findMinInstructionsToMakeReliable 通过不断尝试添加指令,直到找到使给定程序成为可靠的 MIN 程序所需的最少指令数量。

原文