문제 링크: https://www.acmicpc.net/problem/2108
백준 정렬 6단계 - 2108번 통계학을 풀어보았다.
풀이: 평균, 중앙값, 최빈값, 범위를 출력하면 된다. 최빈값 조건이 까다로우니 잘 해결해야 한다.
C++의 경우, https://cryptosalamander.tistory.com/47 를 참조했다.
파이썬의 경우, counter를 이용해 풀었다.
C++
#include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
using namespace std;
vector<int> arr;
int main() {
int num,tmp,range,middle = 0,most_val,mean = 0;
int most = -9999;
int number[8001] = {0,};
bool not_first = false;
cin >> num;
for(int i = 0; i < num; i++)
{
cin >> tmp;
arr.push_back(tmp);
mean += tmp;
number[tmp+4000]++;
}
sort(arr.begin(),arr.end());
for(int i = 0; i < 8001; i++)
{
if(number[i] == 0)
continue;
if(number[i] == most)
{
if(not_first)
{
most_val = i - 4000;
not_first = false;
}
}
if(number[i] > most)
{
most = number[i];
most_val = i - 4000;
not_first = true;
}
}
middle = arr[arr.size()/2];
mean = round((float)mean / num);
range = arr.back() - arr.front();
cout << mean << '\n' << middle << '\n' << most_val << '\n' << range;
}
Python
import sys
from collections import Counter
n = int(sys.stdin.readline())
inp = []
for i in range(n):
inp.append(int(sys.stdin.readline()))
inp.sort()
cnt=Counter(inp).most_common()
ncnt=0
if len(cnt)>1: # 최빈값이 두개 이상이면
if cnt[0][1]==cnt[1][1]: ncnt=cnt[1][0] # 빈도가 같다면 두번째꺼
else: ncnt=cnt[0][0]
else: ncnt=cnt[0][0]
print(round(sum(inp)/n))
print(inp[n//2])
print(ncnt)
print(inp[-1]-inp[0])
Java
'코테용 문제풀이 > 백준' 카테고리의 다른 글
좌표 정렬하기 풀이 (0) | 2023.01.04 |
---|---|
소트인사이드 풀이 (0) | 2023.01.04 |
수 정렬하기 3 풀이 (0) | 2023.01.04 |
수 정렬하기 2 풀이 (0) | 2023.01.04 |
커트라인 풀이 (0) | 2023.01.04 |