你没有考虑石头重量相同的情况
时间: 2024-02-11 20:04:32 浏览: 38
非常抱歉,我的确没有考虑石头重量相同的情况。在存在石头重量相同的情况下,需要使用一个 multiset 来存储石头的重量和下标,遍历每个石头时,检查其前后是否存在重量差为D的石头对。
具体实现如下:
```c++
#include <iostream>
#include <set>
using namespace std;
void findPairs(int stones[], int n, int d) {
multiset<pair<int, int>> s; // 存储石头的重量和下标
for(int i = 0; i < n; i++) {
int stone = stones[i];
auto it = s.find({stone-d, -1}); // 找到一个重量差为D的石头对
while(it != s.end() && it->first == stone-d) {
if(it->second != i) { // 排除相同下标的石头
cout << "(" << stone << ", " << it->first << ")" << endl;
}
it++;
}
it = s.find({stone+d, -1}); // 找到一个重量差为D的石头对
while(it != s.end() && it->first == stone+d) {
if(it->second != i) { // 排除相同下标的石头
cout << "(" << stone << ", " << it->first << ")" << endl;
}
it++;
}
s.insert({stone, i}); // 将该石头的重量和下标插入到集合中
}
}
int main() {
int stones[] = {1, 3, 5, 6, 8, 5};
int n = sizeof(stones) / sizeof(stones[0]);
int d = 3;
findPairs(stones, n, d);
return 0;
}
```
由于 multiset 可以存储相同的元素,因此可以处理石头重量相同的情况。遍历每个石头时,分别在 multiset 中查找重量为 stone-d 和 stone+d 的石头,如果存在则输出石头对。需要注意的是,由于 multiset 中可能存在相同的重量,因此需要遍历所有重量为 stone-d 和 stone+d 的石头,排除相同下标的石头。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)