C++编程练习
·
1. 题目1
8个球找出那个偏重的球,其他7个球重量一样,有天平称重左右两边
//
// Created by ZhuanZ1 on 2026/6/23.
//
#include <iostream>
#include <vector>
using namespace std;
#include <optional>
// 模拟天平的三种状态(三进制信息源)
enum class ScaleState {
LEFT_HEAVY, // 左重
BALANCED, // 平衡(核心排除状态)
RIGHT_HEAVY // 右重
};
// 模拟天平称重函数
// left_indices: 左盘球的索引集合
// right_indices: 右盘球的索引集合
// weights: 所有球的实际重量数组
ScaleState weigh(const vector<int>& left_indices,
const vector<int>& right_indices,
const vector<int>& weights)
{
int left_sum = 0, right_sum = 0;
for (int idx : left_indices) left_sum += weights[idx];
for (int idx : right_indices) right_sum += weights[idx];
if (left_sum == right_sum) return ScaleState::BALANCED;
return (left_sum > right_sum) ? ScaleState::LEFT_HEAVY : ScaleState::RIGHT_HEAVY;
}
// 核心求解函数:返回异常球的索引
int findAbnormalBall(const vector<int>& weights) {
// 【第1次称重】左3 vs 右3
vector<int> left = {0, 1, 2};
vector<int> right = {3, 4, 5};
ScaleState state1 = weigh(left, right, weights);
if (state1 == ScaleState::BALANCED) {
// 异常球在 {6, 7} 中,已知偏重
ScaleState state2 = weigh({6}, {0}, weights); // 0是已知正常球
return (state2 == ScaleState::BALANCED) ? 7 : 6;
}
// 已知偏重,所以哪边重,异常球就在哪边
vector<int> suspect3 = (state1 == ScaleState::LEFT_HEAVY) ? vector<int>{0, 1, 2} : vector<int>{3, 4, 5};
// 【第2次称重】从3个嫌疑球中取2个对比
ScaleState state2 = weigh({suspect3[0]}, {suspect3[1]}, weights);
if (state2 == ScaleState::BALANCED) return suspect3[2]; // 没上秤的那个
if (state2 == ScaleState::LEFT_HEAVY) return suspect3[0]; // 左重→左边是重球
return suspect3[1]; // 右重→右边是重球
}
int main() {
// 测试用例:8个球,正常重量为10,异常球(索引7)重量为12
vector<int> balls = {10, 10, 10, 10, 10, 10, 10, 12};
vector<int> balls2 = {10, 12, 10, 10, 10, 10, 10, 10};
int result = findAbnormalBall(balls2);
if (result != -1) {
std::cout << "找到异常球!索引: " << result
<< ", 重量: " << balls[result] << std::endl;
}
return 0;
}
更多推荐

所有评论(0)