프로그래밍/알고리즘

BOJ 10825 · 국영수

반응형


알고리즘 분류 : 정렬  


여러 개의 변수가 있는 리스트를 정렬해야 하는 문제다. 이 문제의 경우 국어, 영어, 수학, 이름 순서로 우선순위를 정해서 정렬해야 한다. 크게 두 가지의 방법으로 해결할 수 있다. 우선순위를 따진 연산자 오버로딩을 통한 정렬, 그리고 Set을 이용한 정렬이다.


  • C++의 경우, struct로 여러 개의 변수를 받고, 각 변수에 대한 우선순위를 정해서 연산자 오버로딩을 하여 정렬할 수 있다.
  • C++의 경우, tuple과 set을 활용하여 간단히 구현할 수도 있다.
  • Python의 경우, 변수의 입력 순으로 우선순위를 따져서 자동으로 정렬해준다.
  • 오름차순인지 내림차순인지만 잘 정하면 된다. 기본적으로 정렬 함수가 오름차순으로 작동하므로, 내림차순은 원소를 음수로 처리하면 간편하다.




C++ 소스코드


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

struct score {
    int korean, english, math;
    string name;
    bool operator < (const score &t) const {
        if (korean == t.korean) {
            if (english == t.english) {
                if (math == t.math) {
                    return name.compare(t.name) < 0;
                }
                return math > t.math;
            }
            return english < t.english;
        }
        return korean > t.korean;
    }
    bool operator > (const score &t) const {
        if (korean == t.korean) {
            if (english == t.english) {
                if (math == t.math) {
                    return name.compare(t.name) > 0;
                }
                return math < t.math;
            }
            return english > t.english;
        }
        return korean < t.korean;
    }
};

int n;
vector<score> v;

void solve() {
    cin >> n;
    for (int i=0; i<n; i++) {
        int k, e, m;
        string name;
        cin >> name >> k >> e >> m;
        v.push_back({k, e, m, name});
    }
}

int main() {
    ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
    solve();
    sort(v.begin(), v.end());
    for (auto k : v) {
        cout << k.name << '\n';
    }
    return 0;
}


✓ set과 tuple을 이용하여 구현한 방법이다. set의 insert는 오름차순 정렬을 하면서 원소를 집어넣는다. 때문에 내림차순으로 정렬하려면 음수로 집어넣으면 간단하다.


#include <iostream>
#include <string>
#include <set>
#include <tuple>
using namespace std;

set<tuple<int, int, int, string>> s;

void solve() {
    int n;
    cin >> n;
    for (int i=0; i<n; i++) {
        int k, e, m;
        string name;
        cin >> name >> k >> e >> m;
        s.insert({-k, e, -m, name});
    }
}

int main() {
    ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
    solve();
    for (auto k : s) {
        cout << get<3>(k) << '\n';
    }
    return 0;
}




Python 3 소스코드


from sys import stdin, stdout
input = stdin.readline
print = stdout.write

s = []
for i in range(int(input())):
    n, k, e, m = map(str, input().split())
    s.append((-int(k), int(e), -int(m), n))
s.sort()
for k in s:
    print(k[-1]+'\n')




참고



반응형