Pagini recente » Cod sursa (job #761233) | Cod sursa (job #2642396) | Cod sursa (job #1050617) | Cod sursa (job #2136815) | Cod sursa (job #1184393)
#include <iostream>
#include <fstream>
#include <stack>
#include <queue>
using namespace std;
const int Nmax = 500000 + 1;
struct Node
{
int key;
Node *st, *dr;
Node( int _key, Node *lf, Node *rt )
{
key = _key;
st = lf;
dr = rt;
}
} *root, *NIL;
int N;
int A[Nmax];
void initTree()
{
NIL = new Node( 0, NULL, NULL );
root = NIL;
}
void makeCartesianTree()
{
stack < Node* > ST;
ST.push( NIL );
for ( int i = 1; i <= N; ++i )
{
Node *node = new Node( A[i], NIL, NIL );
Node *curr;
for ( curr = ST.top(); curr != NIL; ST.pop(), curr = ST.top() )
if ( curr->key < A[i] ) break;
if ( curr == NIL )
{
node->st = root;
root = node;
}
else
{
node->st = curr->dr;
curr->dr = node;
}
ST.push( node );
}
}
class cmp
{
public:
bool operator() ( const Node *a, const Node *b ) const
{
return a->key > b->key;
}
};
void CartesianTreeSort()
{
ofstream g("algsort.out");
priority_queue < Node*, vector<Node*>, cmp > Q;
Q.push( root );
for ( int i = 1; i <= N; ++i )
{
Node *nod = Q.top();
Q.pop();
g << nod->key << " ";
if ( nod->st != NIL ) Q.push( nod->st );
if ( nod->dr != NIL ) Q.push( nod->dr );
}
}
int main()
{
ifstream cin("algsort.in");
cin >> N;
for ( int i = 1; i <= N; ++i )
cin >> A[i];
initTree();
makeCartesianTree();
CartesianTreeSort();
return 0;
}