ヒープの使い方?

フォーラム(掲示板)ルール
フォーラム(掲示板)ルールはこちら  ※コードを貼り付ける場合は [code][/code] で囲って下さい。詳しくはこちら
よっしー

ヒープの使い方?

#1

投稿記事 by よっしー » 2年前

「ベクターS(N)について、前からi番目まで入力したとき、k番目に小さい数を出力する」プログラムを作ったつもりなのですが、「S(N)=10,9,8,7,6,5,4,3,2,1」のとき、出力「10,10,10,9,8,7,6,5,4,3」を期待しているのに「10,10,10,9,8,7,7,6,6,5」となってしまいます。if、elseで意図しない場所に行っていないかチェックするため、a,b,cを出力させているのですが、意図した通りに動いているように見えます。不具合の原因がわからず、一週間近く時間を無駄にしていて途方に暮れています。どなたか教えていただけませんでしょうか。どうかよろしくお願いいたします。

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

struct Heap_Max
{
vector<int> heap;
Heap_Max() {}

void push(int x)
{
heap.push_back(x);
int i = (int)heap.size() - 1;
while (i > 0)
{
int p = (i - 1) / 2;
if (heap[p] >= x)
break;
heap = heap[p];
i = p;
}
heap = x;
}
int top()
{
if (!heap.empty())
return heap[0];
else
return -1;
}
void pop()
{
if (heap.empty())
return;
int x = heap.back();
int i = 0;
while (i * 2 + 1 < (int)heap.size())
{
int child1 = i * 2 + 1, child2 = i * 2 + 2;
if (child2 < (int)heap.size() && heap[child2] > heap[child1])
{
child1 = child2;
}
if (heap[child1] <= x)
break;
heap = heap[child1];
i = child1;
}
heap = x;
}
};
struct Heap_Min
{
vector<int> heap;
Heap_Min() {}

void push(int x)
{
heap.push_back(x);
int i = (int)heap.size() - 1;
while (i > 0)
{
int p = (i - 1) / 2;
if (heap[p] <= x)
break;
heap = heap[p];
i = p;
}
heap = x;
}
int top() //最小値を取得
{
if (!heap.empty())
return heap[0];
else
return -1;
}
void pop() //最小値を削除
{
if (heap.empty())
return;
int x = heap.back();
int i = 0;
while (i * 2 + 1 < (int)heap.size())
{
int child1 = i * 2 + 1, child2 = i * 2 + 2;
if (child2 < (int)heap.size() && heap[child2] < heap[child1])
{
child1 = child2;
}
if (heap[child1] <= x)
break;
heap = heap[child1];
i = child1;
}
heap = x;
}
};

int main()
{
int N, k;
cin >> N >> k;

vector<int> S(N);
for (int i = 0; i < N; ++i)
{
cin >> S;
}

Heap_Max low;
Heap_Min high;
for (int i = 0; i < N; ++i)
{
if (i < k)
{
cout << "a" << endl;
low.push(S);
}
else
{
int M = low.top(); //Mはlowの最大値であり、k番目に小さい数
if (S[i] >= M)
{
high.push(S[i]);
cout << "b" << endl;
}
else
{
low.push(S[i]);
low.pop();
cout << "c" << endl;
}
}
cout << i << ":" << low.top() << endl;
}
}

よっしー

Re: ヒープの使い方?

#2

投稿記事 by よっしー » 2年前

上記、書き漏らしました。すみません。S(N)=10,9,8,7,6,5,4,3,2,1 k=3の入力です。

よっしー

Re: ヒープの使い方?

#3

投稿記事 by よっしー » 2年前

申し訳ありません。初投稿で意図した通りの表示にできていませんでした。
削除しようとしたのですが、方法が分からなかったので、改めて新しい投稿をさせてもらいます。
この板は削除方法が分かり次第削除しますので、ご容赦お願いします。

返信

“C言語何でも質問掲示板” へ戻る