Cod sursa(job #2902540)

Utilizator andrei_C1Andrei Chertes andrei_C1 Data 16 mai 2022 15:48:34
Problema Elementul majoritar Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.27 kb
// am implementat elmaj online in O(QlogN)
#include <bits/stdc++.h>

using namespace std;

ifstream fin("elmaj.in");
ofstream fout("elmaj.out");

struct Node {
    int key;
    int freq;
    int subtreeSize;
    Node *left, *right;
};

Node *root;

void Insert(int val){
    if(root == NULL) {
        root = new Node;
        root->key = val;
        root->freq = 1;
        root->subtreeSize = 1;
        root->left = root->right = NULL;
        return;
    }

    Node *p, *q;
    q = p = root;

    while(p != NULL) {
        (p->subtreeSize)++;

        if(val == p->key) {
            (p->freq)++;
            return;
        }

        q = p;

        if(val < p->key) {
            p = p->left;
        } else {
            p = p->right;
        }
    }

    p = new Node;
    p->key = val;
    p->freq = p->subtreeSize = 1;
    p->left = p->right = NULL;

    if(val < q->key) {
            q->left = p;
    } else {
        q->right = p;
    }
}

void Inord(Node *root) {
    if(root != NULL) {
        Inord(root->left);
        cout << root->key << " " << root->freq << " " << root->subtreeSize << '\n';
        Inord(root->right);
    }
}

Node *Search(Node *root, int k) {
    int v;
    while(root != NULL) {
        if(root->left != NULL && k <= root->left->subtreeSize) {
            root = root->left;
        } else {
            if(root->left == NULL) {
                v = 0;
            } else {
                v = root->left->subtreeSize;
            }

            k -= v;

            if(k <= root->freq) {
                return root;
            }
            k -= root->freq;

            root = root->right;
        }
    }

    return 0;
}

pair<int, int> MajorityQuery(Node *root) {
    int med = root->subtreeSize / 2;
    Node *val = Search(root, med);
    if(val->freq > med) {
        return {val->key, val->freq};
    }
    return {-1, -1};
}

int N;

int main() {
    fin >> N;

    for(int i = 1; i <= N; i++) {
        int val;
        fin >> val;

        Insert(val);
    }

    pair<int, int> ans = MajorityQuery(root);

    if(ans.first != -1) {
        fout << ans.first << " " << ans.second << '\n';
    } else {
        fout << "-1\n";
    }
    return 0;
}