c++有一个老板有一袋金块。每个月将有两名雇员会因其优异的表现分别被奖励一个金块。
时间: 2024-06-14 21:05:53 浏览: 130
以下是使用C++解决这个问题的示例代码:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
struct GoldBlock {
int weight;
int index;
};
// 比较函数,用于排序
bool compareGoldBlock(const GoldBlock& block1, const GoldBlock& block2) {
return block1.weight < block2.weight;
}
// 找出最轻和最重的金块
void findLightestAndHeaviestGoldBlocks(const std::vector<int>& goldWeights) {
int n = goldWeights.size();
std::vector<GoldBlock> blocks(n);
// 初始化金块信息
for (int i = 0; i < n; i++) {
blocks[i].weight = goldWeights[i];
blocks[i].index = i + 1;
}
// 排序金块
std::sort(blocks.begin(), blocks.end(), compareGoldBlock);
// 输出结果
std::cout << "最轻的金块是:" << blocks[0].index << ",重量为:" << blocks[0].weight << std::endl;
std::cout << "最重的金块是:" << blocks[n-1].index << ",重量为:" << blocks[n-1].weight << std::endl;
}
int main() {
int n;
std::cin >> n;
std::vector<int> goldWeights(n);
for (int i = 0; i < n; i++) {
std::cin >> goldWeights[i];
}
findLightestAndHeaviestGoldBlocks(goldWeights);
return 0;
}
```
阅读全文