Cod sursa(job #2902743)

Utilizator andrei_C1Andrei Chertes andrei_C1 Data 16 mai 2022 19:22:51
Problema Elementul majoritar Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.25 kb
#include <bits/stdc++.h>
 
#pragma GCC optimize("Ofast")
 
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);
    }
}
 
 pair<int, int> 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->key, root->freq};
            }
            k -= root->freq;
 
            root = root->right;
        }
    }
 
    return {-1, 0};
}
 
pair<int, int> MajorityQuery(Node *root) {
    int med = root->subtreeSize / 2;
    pair<int, int> val = Search(root, med);
    if(val.second > med) {
        return val;
    }
    return {-1, 0};
}
 
int N;
 
int main() {
    ios_base :: sync_with_stdio(false); fin.tie(0); fout.tie(0);
 
    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;
}