Pagini recente » Cod sursa (job #709467) | Cod sursa (job #1395977) | Cod sursa (job #1631616) | Cod sursa (job #567450) | Cod sursa (job #1074988)
#include <cstdio>
const int NMAX = 100000;
using namespace std;
#define max(a, b) a > b ? a : b
typedef struct node{
node *left, *right, *prev;
int value;
int max;
} node;
int N, max, MAX;
int solution[NMAX];
node *root;
node *maxNode;
inline int getHeight(node *nod) {
if ( !nod )
return 0;
else {
int a = getHeight(nod -> left);
int b = getHeight(nod -> right);
int k = ( max(a, b) ) + 1;
return k;
}
}
node* rebalance(node *nod) {
if( nod == NULL)
return NULL;
else {
node *aux = nod;
if( getHeight(nod -> left) - getHeight(nod -> right) > 1 ) {
if( getHeight(nod -> left -> left) - getHeight(nod -> right) > 0){
aux = nod -> left;
nod -> left = aux -> right;
aux -> right = nod;
} else {
aux = nod -> left -> right;
nod -> left -> right = aux -> left;
aux -> left = nod -> left;
nod -> left = aux -> right;
aux -> right = nod;
}
} else if ( getHeight(nod -> right) - getHeight(nod -> left) > 1 ) {
if ( getHeight(nod -> right -> right) - getHeight(nod -> left) > 0 ) {
aux = nod -> right;
nod -> right = aux -> left;
aux -> left = nod;
} else {
aux = nod -> right -> left;
nod -> right -> left = aux -> right;
aux -> right = nod -> right;
nod -> right = aux -> left;
aux -> left = nod;
}
}
return aux;
}
}
node* insert(node *nod, int value, node *prev) {
if( nod == NULL ) {
nod = new node;
nod -> value = value;
nod -> prev = prev;
nod -> left = nod -> right = NULL;
if ( prev != NULL )
nod -> max = prev -> max + 1;
else
nod -> max = 1;
if (nod -> max >= MAX) {
MAX = nod -> max;
maxNode = nod;
}
} else {
if( nod -> value > value) {
nod -> left = insert(nod -> left, value, prev);
} else {
if( nod -> value < value && (!prev || nod -> max > prev -> max))
nod -> right = insert( nod -> right, value, nod);
else
nod -> right = insert( nod -> right, value, prev);
}
}
nod = rebalance(nod);
return nod;
}
void printSolution() {
int k = 0;
while( maxNode ) {
solution[k++] = maxNode -> value;
maxNode = maxNode -> prev;
}
printf("%i\n", MAX);
for(int i = MAX - 1; i >= 0; i--)
printf("%i ", solution[i]);
}
void printTree(node *nod) {
if( nod ) {
printf("%i L(", nod -> value);
printTree(nod -> left);
printf(") R(");
printTree(nod -> right);
printf(")");
}
}
void read() {
freopen( "scmax.in", "r", stdin );
freopen( "scmax.out", "w", stdout );
scanf("%i", &N);
int x;
for(int i = 0; i < N; i++) {
scanf("%i", &x);
root = insert(root, x, NULL);
}
}
int main() {
read();
printSolution();
return 0;
}