-
[백준 2108] 통계학백준/자료구조 2023. 10. 26. 23:13
알고리즘 중간고사에서 key-value 쌍이 주어지고 value 값에 대한 두번째 최빈값 구하는 문제가 나왔는데 생각보다 오래걸렸다.
그래서 그나마 비슷한 문제를 풀어봄.
시험때는 map을 못쓰게해서 heap으로 어찌저찌 풀어놓긴 했는데 일단 map으로 하면 됨.
map으로 받고 vector로 바꾸고 정렬기준 만들어서 정렬해주면 된다.
참고로 정렬기준은 true를 반환하는게 우선순위가 높은거임
#include <iostream> #include <algorithm> #include <vector> #include <unordered_map> #include <cmath> using namespace std; int N, x; 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() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int mean = 0; int common2; vector<int> v; unordered_map<int, int> m; cin >> N; if (N == 1) { cin >> x; cout << x << "\n" << x << "\n" << x << "\n" << 0; return 0; } for (int i = 0; i < N; i++) { cin >> x; mean += x; v.push_back(x); m[x]++; } // 배열 정렬(오름차순) sort(v.begin(), v.end()); // map -> vector vector<pair<int, int>> ans(m.begin(), m.end()); // value 값으로 정렬 sort(ans.begin(), ans.end(), comp); // 두번째 작은 빈도수 찾기 if (ans[0].second != ans[1].second) { common2 = ans[0].first; } else common2 = ans[1].first; mean = round(float(mean) / N); cout << mean << "\n" << v[N / 2] << "\n" << common2 << "\n" << v.back() - v.front(); return 0; }'백준 > 자료구조' 카테고리의 다른 글
[백준 1181] 단어 정렬 (1) 2025.02.03 [백준 1539] 이진 검색 트리 (2) 2024.02.09 [백준 25758] 유전자 조합 (0) 2024.02.06 [백준 2002] 추월 (1) 2024.01.10 [백준 13414] 수강신청 (0) 2023.03.31