Cod sursa(job #2284917)

Utilizator theodor.moroianuTheodor Moroianu theodor.moroianu Data 17 noiembrie 2018 19:07:11
Problema Sortare prin comparare Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.02 kb
#include <bits/stdc++.h>
using namespace std;

typedef struct Pheap * Arbore;
struct Pheap {
	int val;
	Arbore fiu, next;
	Pheap(int x) : val(x), fiu(0), next(0) { }
};

Arbore join(Arbore a, Arbore b)
{
	if (a == 0)
		return b;
	if (b == 0)
		return a;
	if (a->val > b->val) {
		b->next = a->fiu;
		a->fiu = b;
		return a;
	}
	a->next = b->fiu;
	b->fiu = a;
	return b;
}

Arbore rem_min(Arbore a)
{
	Arbore ans = 0, act = 0;
	for (Arbore i = a->fiu; i; ) {
		Arbore x = i;
		i = i->next;
		x->next = 0;
		if (act) {
			ans = join(ans, join(act, x));
			act = 0;
		}
		else
			act = x;
	}
	return join(ans, act);
}


int main()
{
    FILE *in = fopen("algsort.in", "r");
    FILE *out = fopen("algsort.out", "w");

	int n, x;
	fscanf(in, "%d", &n);

    Arbore act = 0;

    while (n--) {
        fscanf(in, "%d", &x);
        act = join(act, new Pheap(-x));
    }

    while (act) {
        fprintf(out, "%d ", -act->val);
        act = rem_min(act);
    }

	return 0;

}