Official

B - Do you know the second highest mountain? Editorial by en_translator


It is sufficient to sort the \(N\) mountains in the decreasing order with the priority of (height -> name), and then output the name of the second mountain.

The complexity is \(O(M \log N)\), where \(M\) is (sum of lengths of \(S_i\)).

Sample Code (C++)

#include<bits/stdc++.h>
using namespace std;

int main(){
    int N; cin >> N;
    vector<pair<int,string>> data(N);
    for(int i=0; i<N; i++) cin >> data[i].second >> data[i].first;
    sort(data.begin(),data.end(),std::greater{});
    cout << data[1].second << endl;
}

Sample Code (Python)

N = int(input())
data = []
for i in range(N):
    S,T = map(str,input().split())
    T = int(T)
    data.append([T,S])
data.sort(reverse=True)
print(data[1][1])

Note that this problem can also be solved in a total of \(O(M)\) time by incrementally updating the data of the first and second highest mountains.

Sample Code (C++)

#include<bits/stdc++.h>
using namespace std;

int main(){
    int N; cin >> N;
    vector<string> S(N);
    vector<int> T(N);
    pair<int,string> top,sec;
    top = sec = {0,""};
    for(int i=0; i<N; i++){
        cin >> S[i] >> T[i];
        auto p = make_pair(T[i],S[i]);
        if(top < p){
            sec = top;
            top = p;
        }
        else if(sec < p){
            sec = p;
        }
    }
    cout << sec.second << endl;
}

posted:
last update: