Some stuff.

#include <iostream>
using namespace std;
int a[20000];
bool in_heap[20000];
int n;

inline void swap(int& x, int& y)
{
int tmp = x;
x = y;
y = tmp;
}

void maintain(int i)
{
    /*cout << endl << endl;
    cout << "Maintaining node " << i << endl;
    cout << "Current heap: ";
    cout << a[1];
    for(int i = 2; i <= n; i++) cout << ", " << a[i];
    cout << endl;*/
    while(i < n)
    {
        int m, c;
        /*cout << "\tStats:" << endl;
        cout << "\t\tCurrently at node " << i << endl;
        cout << "\t\tCurrent node value: " << a[i] << endl;
        cout << "\t\tParent: " << i/2 << endl;
        cout << "\t\tLeft child: " << 2*i << endl;
        cout << "\t\tRight child: " << 2*i + 1 << endl;
        cout << "\t\tParent value: " << a[i/2] << endl;
        cout << "\t\tLeft child value: " << a[2*i] << endl;
        cout << "\t\tRight child value: " << a[2*i + 1] << endl;*/
        if (a[2*i] < a[2*i + 1]) { m = a[2*i + 1]; c = 1; }
        else { m = a[2*i]; c = 0; }
        /*cout << "\tm is " << m << endl;
        cout << "\tselected node is " << 2*i + c << endl;*/
        if(m != 0)
        {
            if(m > a[i]) { /*cout << "\tswapped " << 2*i + c << " and " << i << endl;*/ swap(a[2*i + c], a[i]); i = 2*i + c; }
            else
            {
                //cout << "\t" << 2*i + c << " is disqualified." << endl;
                c = (c + 1)%2;
                m = a[2*i + c];
                /*cout << "\t\tnew: " << endl;
                cout << "\t\tm is " << m << endl;
                cout << "\t\tselected node is " << 2*i + c << endl;*/
                if(m > a[i]) { /*cout << "\t\tswapped " << 2*i + c << " and " << i << endl;*/ swap(a[2*i + c], a[i]); i = 2*i + c; }
                else { /*cout << "\t\tin correct place now, breaking" << endl;*/ break; }
            }
        }
        else { /*cout << "\tlargest is 0 already, break" << endl;*/ break; }
        /*cout << "\tCurrent heap: ";
        cout << a[1];
        for(int i = 2; i <= n; i++) cout << ", " << a[i];
        cout << endl;*/
    }
    /*cout << "Result after maintaing heap: ";
    cout << a[1];
    for(int i = 2; i <= n; i++) cout << ", " << a[i];
    cout << endl << endl << endl;*/
}

int main()
{
    cout << "Heap size: ";
    cin >> n;
    cout << "Values: ";
    for(int i = 1; i <= n; i++) cin >> a[i];
    for(int ind = n/2; ind > 0; ind--) maintain(ind);
    cout << "Sorting: " << endl;
    while(n > 0)
    {
    cout << a[1] << " ";
    a[1] = a[n--];
        a[n + 1] = 0;
    maintain(1);
    }
    cout << endl;
}

Comments

Popular posts from this blog

USACO Training "subset": Subset Sums

USACO 2018 Open: Talent Show

OpenJudge 1768: Kadane's Algorithm on 2D Arrays