Pagini recente » Cod sursa (job #2186130) | Cod sursa (job #2130107) | Cod sursa (job #2854457) | Cod sursa (job #351947) | Cod sursa (job #653436)
Cod sursa(job #653436)
#include <fstream>
#include <string>
#include <sstream>
#define max(a, b) (((a) > (b)) ? (a) : (b))
using namespace std;
class avl
{
private:
struct node
{
unsigned int info;
unsigned int app;
node * left;
node * right;
};
bool found;
int insertions;
node * root;
node * NIL;
node * create(unsigned int value)
{
node * p = new node;
p->info = value;
p->app = 1;
p->left = p->right = this->NIL;
return p;
}
unsigned int height(node * parent)
{
return (parent != this->NIL)
? 1 + max(this->height(parent->left), this->height(parent->right))
: 0;
}
node * rotate_left(node * parent)
{
node * t = parent->left;
parent->left = t->right;
t->right = parent;
return t;
}
node * rotate_right(node * parent)
{
node * t = parent->right;
parent->right = t->left;
t->left = parent;
return t;
}
node * balance(node * parent)
{
if (this->height(parent->left) > this->height(parent->right) + 1)
{
if (this->height(parent->left->right) > this->height(parent->left->left))
parent->left = this->rotate_right(parent->left);
parent = this->rotate_left(parent);
}
else if (this->height(parent->right) > this->height(parent->left) + 1)
{
if (this->height(parent->right->left) > this->height(parent->right->right))
parent->right = this->rotate_left(parent->right);
parent = this->rotate_right(parent);
}
return parent;
}
node * insert(node * parent, unsigned int value)
{
if (parent == this->NIL)
return this->create(value);
if (value < parent->info)
parent->left = this->insert(parent->left, value);
else if (value > parent->info)
parent->right = this->insert(parent->right, value);
else
parent->app += 1;
return this->balance(parent);
}
void get_elmaj(node * parent, unsigned int & max, string & msg)
{
stringstream ss;
if (parent != this->NIL && parent->app > max)
{
if (!this->found)
this->found = true;
ss << parent->info << " " << parent->app;
msg = ss.str();
max = parent->app;
ss.clear();
}
if (parent == this->NIL)
return;
this->get_elmaj(parent->left, max, msg);
this->get_elmaj(parent->right, max, msg);
}
public:
avl()
{
this->NIL = new node;
this->NIL->info = this->NIL->app = 0;
this->NIL->left = this->NIL->right = NULL;
this->root = this->NIL;
this->insertions = 0;
this->found = false;
}
void insert(unsigned int value)
{
this->root = this->insert(this->root, value);
this->insertions += 1;
}
string get_elmaj()
{
unsigned int max = 0;
string msg;
//this->get_elmaj(this->root, max, msg);
return this->found ? (max > (this->insertions >> 1) ? msg : "-1") : "-1";
}
};
int main()
{
unsigned int i;
unsigned int n, a;
avl * _avl = new avl();
ifstream f("elmaj.in");
ofstream g("elmaj.out");
f >> n;
for (i = 0; i < n; ++i)
{
f >> a;
_avl->insert(a);
}
g << _avl->get_elmaj();
g.close();
f.close();
}