Koala - 13기/코딩테스트 준비 스터디

[백준/C++] 10825번: 국영수

소코기 2024. 2. 16. 16:17

https://www.acmicpc.net/problem/10825

 

10825번: 국영수

첫째 줄에 도현이네 반의 학생의 수 N (1 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 한 줄에 하나씩 각 학생의 이름, 국어, 영어, 수학 점수가 공백으로 구분해 주어진다. 점수는 1보다 크거나 같고, 1

www.acmicpc.net

  • 코드
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <stdio.h>
#include <queue>
#include <vector>
#include <unordered_map>
#include <set>
#include <map>
#include<cmath>
#include<stack>
#include<deque>
#define LL long long
using namespace std;

struct Student {
	string nam;
	int kor;
	int eng;
	int mat;
};

bool compare(Student a, Student b)
{
	if (a.kor == b.kor && a.eng == b.eng && a.mat == b.mat) {
		return a.nam < b.nam;

	}
	else if (a.kor == b.kor && a.eng == b.eng) {
		return a.mat > b.mat;
	}
	else if (a.kor == b.kor) {
		return a.eng < b.eng;
	}
	else return a.kor > b.kor;
}

Student student[100000];
int main() {
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
	
	int n = 0;
	cin >> n;
	
	for (int i = 0; i < n; i++) {
		cin >> student[i].nam >> student[i].kor >> student[i].eng >> student[i].mat;
		
	}
	
	sort(student, student+n,compare);
	
	for (int i = 0; i < n; i++) {
		cout << student[i].nam << "\n";
	}
	
	return 0;
}
  • 알고리즘 분류 : 정렬 (sort(),compare)
  • 문제 해설

c++의 sort 함수 compare 기능을 알아야 풀 수 있는 문제였다. 또한 이 문제의 경우 구조체 개념도 요구한다. 그동안 오름차순 내림차순 정렬이 필요할 때 직접 버블 정렬을 구현해서 풀었는데 sort함수의 시간 복잡도가 nlogn으로 버블 정렬보다 빠르다는 것을 첨 알았다. 앞으로 정렬을 직접 구현할 경우는 없을 것 같다...

이 문제는 sort함수를 쓰는 것이 전부이기 때문에 sort함수에 대해 설명하자면

구현이 필요없이 정렬만 할 경우 sort(배열,배열+배열길이)로 인자를 구성하면 되지만 내부에서 구현이 필요할 경우 구현할 함수 이름을 인자로 더 넘겨야 한다. 구현할 함수의 이름이 compare일 경우

bool compare(정렬될 요소1,정렬될 요소2){

if (조건) 

return (두 요소의 기존 위치를 바꿀꺼면 0 반환하도록, 안바꿀거면 1 반환하도록)

}

이렇게 구성된다.