[ BOJ / C++ ] 11557번 Yangjojang of The Year

황승환·2021년 9월 21일
0

C++

목록 보기
54/65

이번 문제는 정렬로 간단하게 해결하였다.

  • 학교명과 술 소비량을 같이 저장하기 위해 vector<pair<string, int>>형을 사용한다.
  • 술 소비량으로 내림차순 정렬을 해야하므로 compare함수를 작성하였다.
    bool compare(pair<string, int> a, pair<string, int> b){
        return a.second>b.second;
    }
  • STL의 sort함수에 compare을 넣어 내림차순 정렬한다.
  • 벡터의 첫번째 원소의 first를 출력한다.

compare함수에서 오름차순으로 정렬하고 싶다면 return a.second>b.secondreturn a.second<b.second로 변경해주면 된다.

Code

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

int t, n;
vector<pair<string, int>> yj;

void Input(){
    cin>>n;
    for(int i=0; i<n; i++){
        string a;
        int b;
        cin>>a>>b;
        yj.push_back(make_pair(a, b));
    }
}

bool compare(pair<string, int> a, pair<string, int> b){
    return a.second>b.second;
}

void Solution(){
    sort(yj.begin(), yj.end(), compare);
    cout<<yj[0].first<<endl;
}

void Solve(){
    cin>>t;
    for(int i=0; i<t; i++){
        Input();
        Solution();
    }
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    Solve();
    return 0;
}

profile
꾸준함을 꿈꾸는 SW 전공 학부생의 개발 일기

0개의 댓글