Cod sursa(job #2045099)

Utilizator SlevySlevoaca Stefan-Gabriel Slevy Data 21 octombrie 2017 20:23:31
Problema Sortare prin comparare Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.37 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <stack>
#include <functional>
#include <algorithm>

using namespace std;

typedef pair<int, int> ipair;

template <bool reverse = false> struct compare {

	bool operator() (const ipair& f, const ipair& s) const {

		if (reverse == false)
			return less<int>()(f.second, s.second);
		return greater<int>()(f.second, s.second);
	}
};

priority_queue<ipair, vector<ipair>, compare<false>> max_heap;
priority_queue<ipair, vector<ipair>, compare<true>> min_heap;
vector<stack<int>> subsets;
vector<int> sol;

int main() {

	int n, x, indx;
	ifstream in("algsort.in");

	for (in >> n; n; --n) {

		in >> x;

		if (!max_heap.empty() && max_heap.top().second >= x) {

			indx = max_heap.top().first;
			max_heap.pop();

		} else {

			indx = subsets.size();
			subsets.push_back(stack<int>());
		}

		max_heap.emplace(indx, x);
		subsets[indx].push(x);
	}
	in.close();

	while (!max_heap.empty()) {

		min_heap.push(max_heap.top());
		max_heap.pop();
	}
	
	ofstream out("algsort.out");

	while (!min_heap.empty()) {

		out << min_heap.top().second << " ";
		indx = min_heap.top().first;
		min_heap.pop();
		subsets[indx].pop();

		if (!subsets[indx].empty())
			min_heap.emplace(indx, subsets[indx].top());
	}
	out << "\n";
	out.close();
	return 0;
}