관리 메뉴

Storage Gonie

(4) [C++] 백준 No.10814 : 나이순 정렬 본문

알고리즘/백준풀이8. 정렬

(4) [C++] 백준 No.10814 : 나이순 정렬

Storage Gonie 2019. 5. 14. 21:37
반응형

문제

풀이

# C++(pair, stable_sort(, , 비교함수) 사용)

- 가장 간단

#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>

using namespace std;

bool cmp (pair<int, string> u, pair<int, string> v)
{
    return u.first < v.first;
}

int main()
{
    int T;
    cin >> T;

    vector<pair<int, string>> vec(T);

    for (int i = 0; i < T; i++)
        cin >> vec[i].first >> vec[i].second;

    stable_sort(vec.begin(), vec.end(), cmp);

    for (int i = 0; i < T; i++)
        cout << vec[i].first << " " << vec[i].second << "\n";
}

# C++(pair, stable_sort(, , 람다함수) 사용)

#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>

using namespace std;

int main()
{
    int T;
    cin >> T;

    vector<pair<int, string>> vec(T);

    for (int i = 0; i < T; i++)
        cin >> vec[i].first >> vec[i].second;

    stable_sort(vec.begin(), vec.end(), [](const pair<int, string> u, const pair<int, string> v)->bool{
        return u.first < v.first;
    });

    for (int i = 0; i < T; i++)
        cout << vec[i].first << " " << vec[i].second << "\n";
}

# C++(구조체에 나이, 이름 이외에 가입순서를 변수로 넣어 비교함수로 sort)

#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>

using namespace std;

struct Person{
    int age;
    string name;
    int join;
};

bool cmp(Person u, Person v){
    if(u.age < v.age)
        return true;
    else if (u.age == v.age)
        return u.join < v.join;
    else
        return false;
}

int main()
{
    int T;
    cin >> T;

    vector<Person> vec(T);

    for (int i = 0; i < T; i++){
        cin >> vec[i].age >> vec[i].name;
        vec[i].join = i;
    }

    sort(vec.begin(), vec.end(), cmp);

    for (int i = 0; i < T; i++)
        cout << vec[i].age << " " << vec[i].name << "\n";
}
반응형
Comments