BOJ

[백준][c++] 2108번: 통계학

LEE MINGYU 2024. 10. 1. 15:43

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

문제 해석

  • 산술평균, 중앙값, 최빈값, 범위 구하기

알고리즘 분류

  • 수학
  • 정렬

풀이

  • 배열의 값을 모두 더한후 나눠 산술평균을 구한다
  • 배열을 정렬해 중앙값, 범위를 구한다
  • 정수의 절대값이 4000까지인 점을 참고하여 최빈값을 구한다

코드

#include <iostream>
#include <string>
#include <vector>
#include <cmath> 
#include <algorithm>
#include <unordered_map>
using namespace std;

int n;
double sum = 0;
int arr[800001] = {0, };

void qSort(int A[], int start, int end) {
    if (start >= end) return;

    int pivot = start;
    int i = start + 1;
    int j = end;

    while (i <= j) {
        while (i <= end && A[i] <= A[pivot]) i++;
        while (j > start && A[j] >= A[pivot]) j--;

        if (i > j) {
            swap(A[j], A[pivot]);
        } else {
            swap(A[i], A[j]);
        }
    }

    qSort(A, start, j - 1);
    qSort(A, j + 1, end);
}

int mode(){
    int result;
    int count = 0;
    int cnt2[8001] = {0};
    for (int i = 0; i < n;i++){
        cnt2[arr[i] + 4000]++;
    }
    int max_mode = *max_element(cnt2, cnt2 + 8001);
    for (int i = 0; i < 8001;i++){
        if(cnt2[i] == max_mode){
            count++;
            result = i - 4000;
        }
        if(count == 2){
            break;
        }
    }
    return result;
}

int main() { 
    cin >> n;

    for (int i = 1; i <= n; i++) {
        cin >> arr[i];
        sum += arr[i];
    }

    qSort(arr, 1, n);

    double rounded_avg = round(sum / n);
    if (rounded_avg == -0.0) {
        rounded_avg = 0.0;
    }

    cout << rounded_avg << endl; // 평균
    cout << arr[(n + 1) / 2] << endl; // 중앙값
    cout << mode() << endl; //최빈값
    int range = arr[n] - arr[1];
    cout << range << endl; // 범위

    return 0;
}