min-heap with zero based array C++ - c++

Below is my program to build a min-heap using a 0 based array with standard logic from the book. I am using 2*i+1 for left child and 2*i+2 for right child since its a zero based array, still I am getting a wrong output. What am I missing?
#include <iostream>
#include <vector>
#include <algorithm>
using std::vector;
using std::cin;
using std::cout;
class HeapBuilder {
private:
vector<int> data_;
void WriteResponse() const {
for (int i = 0; i < data_.size(); ++i) {
cout << data_[i] << "\n";
}
}
void ReadData() {
int n;
cin >> n;
data_.resize(n);
for (int i = 0; i < n; ++i)
cin >> data_[i];
}
void MinHeapSort(int index)
{
int left = (2 * index) + 1;
int right = (2 * index) + 2;
int smallest;
if (left < data_.size() && data_[left] < data_[index])
smallest = left;
else
smallest = index;
if (right < data_.size() && data_[right] < data_[index])
smallest = right;
if (smallest != index)
{
swap(data_[smallest], data_[index]);
MinHeapSort(smallest);
}
}
void Heapify() {
for (int i = (data_.size() - 1) / 2; i >= 0; i--)
{
MinHeapSort(i);
}
}
public:
void Solve() {
ReadData();
Heapify();
WriteResponse();
}
};
int main() {
std::ios_base::sync_with_stdio(false);
HeapBuilder heap_builder;
heap_builder.Solve();
return 0;
}

Replaced if (right < data_.size() && data_[right] < data_[index]) with
if (right < data_.size() && data_[right] < data_[smallest])
That worked, silly mistake.

Related

Can't convert memory address to value

thanks for visiting my question! Currently, when I run this code (an implementation of the Set data structure in c++), the memory address of each element in the set is printed instead of the values in the set. To help with debugging, here's my code:
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <cassert>
#define PB push_back
typedef std::vector<int> vint;
class SetBase
{
public:
SetBase() {}
~SetBase() {}
void insert(int x)
{
if (!this->isInSet(x))
{
this->set.PB(x);
}
}
int size()
{
return this->set.size();
}
bool empty()
{
return this->size() == 0;
}
int operator[](int index)
{
if (index >= 0 && index < this->size())
{
return this->set[index];
}
else
{
return -1;
}
}
bool find(int target)
{
sort(this->set.begin(), this->set.end());
int low = 0, high = this->size();
while (low <= high)
{
long long mid = low + (high - low) / 2;
long long guess = this->set[mid];
if (guess == target)
return true;
else if (guess < target)
low = mid + 1;
else
high = mid - 1;
}
return false;
}
int count(int target)
{
int counter = 0;
for (int i = 0; i < this->set.size(); i++)
{
if (this->set[i] == target)
counter++;
}
return counter;
}
bool operator=(SetBase &other)
{
if (other.size() != this->size())
return false;
for (int i = 0; i < other.size(); i++)
{
if (other[i] != this->set[i])
return false;
}
return true;
}
private:
vint set;
bool isInSet(int target)
{
for (int i = 0; i < this->size(); i++)
{
if (set[i] == target)
{
return true;
}
}
return false;
}
};
class Set : public SetBase
{
public:
void set_union(Set *set1, Set *set2, Set &back_insertor)
{
for (int i = 0; i < set1->size(); i++)
{
if (this->isInSet(back_insertor, i))
{
back_insertor.insert(i);
}
}
}
void set_difference(Set set1, Set set2, Set &back_insertor)
{
// set_difference = set1 - set2
}
void set_intersection(Set set1, Set set2, Set &back_insertor)
{
// set_difference = set1 U set2
for (int i = 0; i < set1.size(); i++)
{
for (int j = 0; j < set2.size(); j++)
{
if (set1[i] == set2[j])
{
back_insertor.insert(set1[i]);
}
}
}
}
void printSet(Set *in)
{
for (int i = 0; i < in->size(); i++)
{
std::cout << &in[i] << "\n";
}
}
private:
bool isInSet(SetBase set1, int target)
{
for (int i = 0; i < set1.size(); i++)
{
if (target == set1[i])
{
return true;
}
}
return false;
}
};
int main()
{
Set *set_1 = new Set();
Set *set_2 = new Set();
Set *back = new Set();
for (int i = 1; i <= 10; i++)
set_1->insert(i);
for (int i = 1; i <= 10; i++)
set_2->insert(i);
set_2->insert(11);
set_1->set_union(set_1, set_2, *back);
set_1->printSet(set_1);
delete set_1;
delete set_2;
delete back;
}
When running the set_1->printSet(set_1); line, here's what I get:
0x7fb498c05a20
0x7fb498c05a38
0x7fb498c05a50
0x7fb498c05a68
0x7fb498c05a80
0x7fb498c05a98
0x7fb498c05ab0
0x7fb498c05ac8
0x7fb498c05ae0
0x7fb498c05af8
Even though this works, I would like to print out the values (integer) instead. Any help would be appreciated! Thanks! :)
Inside printSet(), you use &in[i] to print each element.
The & operator returns the address of the object you are referencing. So, instead of getting the value, you are getting its address. You should remove it, eg:
void printSet(Set *in)
{
for (int i = 0; i < in->size(); i++)
{
std::cout << (*in)[i] << "\n";
}
}

Process returned -1073741571 (0xC00000FD) on my c++ code [duplicate]

This question already has an answer here:
Clion exit code -1073741571 (0xC00000FD)
(1 answer)
Closed 2 years ago.
The c++ code below works fine for some inputs, but it is stuck at test 9 (number of inputs here is 6000) where it gives me this message "Process returned -1073741571 (0xC00000FD)".
This code reads information for n babies (their gender and name). Next it counts the appearances of each name then sorts the list of structures according to the appearances. Finally, it removes the duplicates and prints the top m female names and top m male names.
What does this error mean and what do I need to change to eliminate this error?
#include <iostream>
#include <fstream>
#include <algorithm>
#include <string.h>
using namespace std;
ifstream fin("input.txt");
struct baby
{
string gender,name;
int cnt;
};
bool cmp(baby a,baby b)
{
if (a.cnt>b.cnt)
return true;
else if (a.cnt==b.cnt && a.name<b.name)
return true;
return false;
}
int howmany(baby babies[],int n,int i)
{
int cnt=0;
for (int j=0; j<n; j++)
{
if (babies[i].name==babies[j].name && babies[i].gender==babies[j].gender)
{
cnt++;
}
}
return cnt;
}
void getData(baby babies[],int n)
{
for (int i=0; i<n; i++)
{
fin>>babies[i].gender>>babies[i].name;
}
}
int removeDuplicates(baby babies[],int n)
{
int j=0;
for (int i=0; i<n-1; i++)
{
if (babies[i].name!=babies[i+1].name)
babies[j++]=babies[i];
}
babies[j++]=babies[n-1];
return j;
}
int main()
{
int n,i,top,j;
fin>>n>>top;
baby babies[50000];
getData(babies,n);
for (i=0; i<n; i++)
{
babies[i].cnt=howmany(babies,n,i);
}
sort(babies,babies+n,cmp);
j=removeDuplicates(babies,n);
int cnt=0;
for (int i=0; i<j; i++)
{
if (cnt<top)
{
if (babies[i].gender=="F")
{
cout<<babies[i].name<<" ";
cnt++;
}
}
}
cout<<endl;
cnt=0;
for (int i=0; i<j; i++)
{
if (cnt<top)
{
if (babies[i].gender=="M")
{
cout<<babies[i].name<<" ";
cnt++;
}
}
}
return 0;
}
As you can see in Window's NT status reference, error code 0xC00000FD means stack overflow (usually caused by infinite recursion). In your case, it seems that you simply allocate a far too large array on the stack (line 57, baby babies[50000];), which is an array of size 50000*20=1000000. The simplest solution will be a dynamic allocation
baby* babies = new baby[50000];
// Your code here
delete[] babies;
A better solution would be to use std::vector which is a dynamic array that can grow and shrink. The simplest thing to do is to take a vector of size 50000, this way:
#include <vector>
...
std::vector<baby> babies(50000);
However, this is a poor solution as your pre-allocate 50000 elements even though you probably need much much less, and a better solution would be to add an element on-demand, using .push_back(element) method, or in your case, allocate n elements to the vector (impossible in a stack-allocated array).
I added your code with some modifications of mine:
#include <vector>
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
ifstream fin("input.txt");
struct baby
{
string gender;
string name;
int cnt = 0;
};
bool cmp(const baby& a, const baby& b)
{
if (a.cnt > b.cnt) {
return true;
}
return a.cnt == b.cnt && a.name < b.name;
}
bool are_equal(const baby& lhs, const baby& rhs)
{
return lhs.gender == rhs.gender && lhs.name == rhs.name;
}
int howmany(const std::vector<baby>& babies, int i)
{
int cnt = 0;
for (int j = 0; j < babies.size(); j++)
{
if (babies[i].name == babies[j].name && babies[i].gender == babies[j].gender)
{
cnt++;
}
}
return cnt;
}
void getData(std::vector<baby>& babies)
{
for (int i = 0; i < babies.size(); i++)
{
fin >> babies[i].gender >> babies[i].name;
}
}
int removeDuplicates(std::vector<baby>& babies)
{
int j = 0;
for (int i = 0; i < babies.size() - 1; i++)
{
if (babies[i].name != babies[i + 1].name) {
babies[j++] = babies[i];
}
}
babies[j++] = babies.back();
return j;
}
void remove_duplicates_improved(std::vector<baby>& babies)
{
babies.erase(babies.begin(), std::unique(babies.begin(), babies.end(), are_equal));
}
int main()
{
int n;
int top;
fin >> n >> top;
std::vector<baby> babies(n);
getData(babies);
for (int i = 0; i < n; i++)
{
babies[i].cnt = howmany(babies, i);
}
sort(babies.begin(), babies.begin() + n, cmp);
remove_duplicates_improved(babies);
int cnt = 0;
for (int i = 0; i < babies.size(); i++)
{
if (cnt < top)
{
if (babies[i].gender == "F")
{
cout << babies[i].name << " ";
cnt++;
}
}
}
cout << endl;
cnt = 0;
for (int i = 0; i < babies.size(); i++)
{
if (cnt < top)
{
if (babies[i].gender == "M")
{
cout << babies[i].name << " ";
cnt++;
}
}
}
return 0;
}
Good luck

std::vector out of range for min-heap: C++

I've neglected to work on this code (or any other coding projects) for a while, so while I know what is basically wrong with the code, I've been having a hard time finding exactly where the vector is going out of range. I've been running gdb on it all morning to no avail. I'm trying to make a min-heap out of a vector "theData" in C++.
#include <iostream>
#include <vector>
#include <algorithm>
using std::vector;
using std::cin;
using std::cout;
using std::swap;
using std::pair;
using std::make_pair;
class HeapBuilder {
private:
vector<int> data_;
vector< pair<int, int> > swaps_;
void WriteResponse() const {
cout << swaps_.size() << "\n";
for (int i = 0; i < swaps_.size(); ++i) {
cout << swaps_[i].first << " " << swaps_[i].second << "\n";
}
}
void ReadData() {
int n;
cin >> n;
data_.resize(n);
for(int i = 0; i < n; ++i)
cin >> data_[i];
}
void makeMinHeap(vector<int> &theData, int i, int n) {
int minIndex;
int left = 2*i;
int right = 2*i + 1;
if (left < n && theData.at(left) < theData.at(i)) {
minIndex = left;
}
else if (right < n && theData.at(right) < theData.at(i)) {
minIndex = right;
}
if (minIndex != i) {
swap(theData.at(i), theData.at(minIndex));
swaps_.push_back(make_pair(i, minIndex));
makeMinHeap(theData, minIndex, n);
}
}
void GenerateSwaps() {
swaps_.clear();
int size = data_.size();
for (int i = (size/2); i >= 0; i--) {
makeMinHeap(data_, i, size);
}
}
public:
void Solve() {
ReadData();
GenerateSwaps();
WriteResponse();
}
};
int main() {
std::ios_base::sync_with_stdio(false);
HeapBuilder heap_builder;
heap_builder.Solve();
return 0;
}
You are not putting in a check for minIndex.
Look what happens when your left<=n and right <=n both fails, most likely when the whole recursion is about to stop, since you just check
minIndex != i
// ^-- default each time is garbage which in case last>n && right>n leaves it garbage
// hence when it comes to
if(minIndex!=i){
// It's actually true where it was suppose to break out n thus throws out_of_range
}
Quick n easy solution would be to add a flagcheck
bool flagcheck = false;
if(){ flagcheck = true; }
else if(){ flagcheck = true; }
if(minIndex!=i && flagcheck){}

Subgraph with max nodes

I have the graph with N nodes. I have to create the longest subgraph (with max nodes). One node can be connected with only 2 nodes. So which nodes should I take to create this (max) subgraph?
What I'm doing is:
1: From initial node. I start 2 DFS functions. (from anothers nodes only 1).
2: For some node in DFS I use F() function to check all neighbours and find maximum way that I have to go. Then I'm saving the index of the node in which I have to go in index variable and starting DFS from index.
The problem is that this algorithm is too slow. How can I optimize it? Maybe there is special algorithm to find maximum subgraph?
Here is my code:
#include <stdio.h>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
int used[20];
int m[20][20];
int c;
int F(int v) {
used[v] = 1;
int maxn = 0, index = -1, t;
for(int i = 0; i < c; ++i) {
if(!used[i] && m[v][i] == 1) {
t = F(i);
if(t > maxn) {
maxn = t;
index = i;
}
}
}
if(index != -1) {
used[v] = 0;
return maxn + 1;
}
else {
used[v] = 0;
return 1;
}
}
int DFS(int v) {
used[v] = 1;
int maxn = 0, index = -1, t;
for(int i = 0; i < c; ++i) {
if(!used[i] && m[v][i] == 1) {
t = F(i);
if(t > maxn) {
maxn = t;
index = i;
}
}
}
if(index != -1) {
return DFS(index) + 1;
}
else {
return 0;
}
}
int main() {
cin >> c;
for(int i = 0; i < c; ++i) {
for(int j = 0; j < c; ++ j)
cin >> m[i][j];
}
int maxn = DFS(0) + DFS(0) + 1;
cout << maxn << endl;
}

postfix evaluation algorithm

here is my attempt for evaluation postfix evaluation
#include<iostream>
#include<string>
using namespace std;
template<class T>
class Stack
{
private:
T *s;int N;
public:
Stack(int maxn)
{
s=new T[maxn];
N=0;
}
int empty()const
{
return N==0;
}
void push(T k)
{
s[N++]=k;
}
T pop()
{
return s[--N];
}
};
int main()
{
//postfix evaluation
char *a="3+4*5";
int N=strlen(a);
Stack<int>save(N);
for(int i=0;i<N;i++)
{
if(a[i]=='+')
save.push(save.pop()+save.pop());
if(a[i]=='*')
save.push(save.pop()*save.pop());
if((a[i]>='0' && a[i]<='9'))
save.push(0);
while((a[i]>='0' && a[i]<='9'))
save.push(10*save.pop()+(a[i++]-'0'));
}
cout<<save.pop()<<" "<<endl;
return 0;
}
but instead of answer 23 because 4*5+3=23,it gives me answer 5,as i understood,this code gives me this result because,first it checks if there is + mark for i=0,which is not,then it checks if if it is *,this is also not,so it first push 0,then it evaluates 10*0+'3'-'0',which is equal to 3,(it would be pushed in stack),for i=1,a[i] is equal to 3,so it prints 3+, second pop is undefined,so i think it is error,please help me to fix it
This works with a little fix:
#include <iostream>
#include <cstring>
using namespace std;
template<class T>
class Stack
{
private:
T *s;
int N;
public:
Stack(int maxn)
{
s = new T[maxn];
N = 0;
}
int empty()const
{
return N == 0;
}
void push(T k)
{
s[N++] = k;
}
T pop()
{
return s[--N];
}
};
int main()
{
//postfix evaluation
const char *a = "3 4 5*+";
int N = strlen(a);
Stack<int>save(N);
for (int i = 0; i < N; i++)
{
if (a[i]=='+')
save.push(save.pop() + save.pop());
if (a[i]=='*')
save.push(save.pop() * save.pop());
if (a[i] >= '0' && a[i] <= '9')
{
save.push(0);
while (a[i] >= '0' && a[i] <= '9')
save.push(10 * save.pop() + a[i++] - '0');
i--;
}
}
cout << save.pop() << " " << endl;
return 0;
}
Output (ideone):
23
Now, if you remove that i--; which I added, the code will be skipping characters in a[] because of 2 increments of i, in a[i++] and for (int i = 0; i < N; i++).
Without i--; the output is (ideone):
9