-
[ 정렬 ] 성적이 낮은 순서로 학생 출력하기알고리즘/이코테 - 실전 2021. 8. 10. 16:05
난이도 : 하 풀이시간 : 20분 시간제한 : 1초
[ 정렬 ] 성적이 낮은 순서로 학생 출력하기
N명의 학생 정보가 있다. 학생 정보는 학생의 이름과 학생의 성적으로 구분된다. 각 학생의 이름과 성적 정보가 주어졌을 때 성적이 낮은 순서대로 학생의 이름을 출력하는 프로그램을 작성하시오.
:: 입력 조건
첫 번째 줄에 학생의 수 N이 입력된다.(1 <= N <= 100,000)
두 번째 줄부터 N + 1번째 줄에는 학생의 이름을 나타내는 문자열 A와 학생의 성적을 나타내는 정수 B가 공백으로 구분되어 입력된다. 문자열 A의 길이와 학생의 성적은 100 이하의 자연수이다.
:: 출력 조건
모든 학생의 이름을 성적이 낮은 순서대로 출력한다. 성적이 동일한 학생들의 순서는 자유롭게 출력해도 괜찮다.
내 코드
#include <iostream> #include <vector> #include <algorithm> #include <string> using namespace std; #define endl "\n" int main() { int n = 0; cin >> n; vector<pair<string, int>> score; for (int i = 0; i < n; i++) { string name; int s; cin >> name >> s; score.push_back(make_pair(name, s)); } for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if(score[i].second > score[j].second){ pair<string, int> tmp; tmp = score[i]; score[i] = score[j]; score[j] = tmp; } } } for (int i = 0; i < n; i++) { cout << score[i].first << " "; } return 0; }
정답 코드
#include <bits/stdc++.h> using namespace std; class Student { public: string name; int score; Student(string name, int score) { this->name = name; this->score = score; } // 정렬 기준은 '점수가 낮은 순서' bool operator <(Student &other) { return this->score < other.score; } }; int n; vector<Student> v; int main(void) { // N을 입력받기 cin >> n; // N명의 학생 정보를 입력받아 리스트에 저장 for (int i = 0; i < n; i++) { string name; int score; cin >> name >> score; v.push_back(Student(name, score)); } sort(v.begin(), v.end()); // 정렬이 수행된 결과를 출력 for(int i = 0; i < n; i++) { cout << v[i].name << ' '; } }
'알고리즘 > 이코테 - 실전' 카테고리의 다른 글
[ 이진탐색 ] 부품 찾기 (0) 2021.08.10 [ 정렬 ] 두 배열의 원소 교체 (0) 2021.08.10 [ 정렬 ] 위에서 아래로 (0) 2021.08.10 [ DFS | BFS ] 미로 탈출 (0) 2021.07.28 [ DFS | BFS ] 음료수 얼려 먹기 (0) 2021.07.28