본문 바로가기
coding/algorithm

[SW Expert Academy] D2 1204. 최빈수 구하기(c++)

by 눈부신음표 2022. 5. 19.
728x90

*map에서 value 기준으로 정렬하기*

-> vector로 바꿔서 sort 하면 됨!!

 

(SW Expert Academy Level2가 Programmers Level1정도 되는건가? 수업 가기 전 10~20분만에 푼거같음. 재밌다 ㅎㅎ)

 

더보기
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;

bool comp(const pair<int, int>& a, const pair<int, int>& b) {
	if (a.second == b.second) return a.first > b.first;
	return a.second > b.second;
}

int main() {
	int n, tc;
	cin >> n;
	for (int i = 0; i < n; i++) {
		map<int, int> scores;
		cin >> tc;
		int score;
		for (int j = 0; j < 1000; j++) {
			cin >> score;
			scores[score] += 1;
		}

		vector<pair<int, int>> scores_vec(scores.begin(), scores.end());
		sort(scores_vec.begin(), scores_vec.end(), comp);

		cout << "#" << tc << " " << scores_vec[0].first << endl;
	}
}

문제

https://swexpertacademy.com/main/code/problem/problemDetail.do

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com

728x90

[접근 1]

map에 해당하는 점수 count

map<int, int> scores;
cin >> tc;
int score;
for (int j = 0; j < 1000; j++) {
    cin >> score;
    scores[score] += 1;
}

[접근 2]

벡터에 복사해서 넣은 뒤, value 기준으로 정렬 후, 같으면 key 기준으로 정렬

bool comp(const pair<int, int>& a, const pair<int, int>& b) {
	if (a.second == b.second) return a.first > b.first;
	return a.second > b.second;
}

 

vector<pair<int, int>> scores_vec(scores.begin(), scores.end());
sort(scores_vec.begin(), scores_vec.end(), comp);
728x90

댓글