【发布时间】:2021-06-18 16:14:29
【问题描述】:
我正在尝试使用自定义运算符实现优先级队列。该算法试图找到要完成的最小增量,以便数组中没有两个相邻元素的绝对差 > 1。
为此,我得到数组中的最大元素“x”并将其邻居修改为 x-1,然后对其他元素重复相同的操作
代码如下:
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
int arr[100], visited[100];
int sizeOfArray;
struct comp
{
public:
bool operator() (int x1, int x2) {
return arr[x1] < arr[x2];
}
};
int main(){
cin>>sizeOfArray;
priority_queue<int, vector<int>, comp> priorityQue;
for(int i = 0; i < sizeOfArray; i++) {
cin>>arr[i];
priorityQue.push(i);
visited[i]=0;
}
while(!priorityQue.empty()) {
int index = priorityQue.top();
priorityQue.pop();
if(visited[index])
continue;
visited[index]=1;
cout<<"Currently at index: "<<index<<endl;
int currentElement = arr[index];
int dx[] = {-1, 1}; // left and right neighbours
for(int k = 0; k < 2; k++) {
int nextIndex = index + dx[k];
if( nextIndex >= 0 && nextIndex < sizeOfArray &&
(currentElement - arr[nextIndex]) > 1 )
{
arr[nextIndex] = currentElement - 1;
cout<<"Modifying index :"<<nextIndex<<endl;
cout<<"New Array is: ";
// print array
for(int z=0;z<sizeOfArray;z++)
cout<<arr[z]<<" ";
cout<<endl;
priorityQue.push(nextIndex);
cout<<"Pushing index "<<nextIndex<<" to queue"<<endl;
}
}
}
return 0;
}
对于输入:
4
4 1 1 0
输出是:
当前位于索引:0
修改索引:1
新数组是:4 3 1 0
将索引 1 推送到队列
目前在索引:2
目前在索引:1
修改索引:2
新数组是:4 3 2 0
将索引 2 推送到队列
目前处于索引:3
我发现优先级队列没有按照比较器应有的方式提取最大元素。访问索引 0 后,数组变为 4 3 1 0 因此索引 1 应该是下一个,但在这种情况下索引 2 被拾取。
我错过了什么??
【问题讨论】:
-
typedef long long ll;-- 不要这样做 -- 不需要这样的宏。 C++ 有int64_t——它准确地描述了类型。然后是这个#include<bits/stdc++.h>——包括正确的头文件,而不是这个。 -
并且不要使用逗号运算符将表达式“链接”成单个语句,而是使用单独的语句。还要尽量避免使用全局变量和简短的非描述性名称。所有这些都会使您的代码更难阅读、理解、维护和调试。
-
@Someprogrammerdude 已编辑
标签: c++ algorithm stl priority-queue max-heap