Priceless

[백준] 2108번: 통계학 (C++) 1트 본문

Algorithm & Test/백준

[백준] 2108번: 통계학 (C++) 1트

Hyun__ 2023. 8. 9. 23:41

숫자를 입력 받아

 

산술 평균

중앙값

두 번째 최빈값

범위

 

4가지 통계 값을 구하는 문제이다

 

산술 평균은 반올림을 고려하여 진행하면 된다

중앙값 과 범위는 인덱스를 활용한다

최빈값은 기존에 알고 있는 정보로는 부족했다

 

두 번째 최빈값을 구하기 위해 첫 번째 최빈값과 두 번째 최빈값을 저장하는 방식으로 접근 했으나 쉽지 않았다

아래 방법과 같이 구현했지만 최빈값 갱신 과정에서 문제가 발생한 것인가 오답이 나타났다

두 최빈 값을 인덱스 값도 추가하여 구현했지만 별다른 방법이 나타나지 않았다

int count = 1;
    int first_max_same = 1;
    int second_max_same = 0;
    int temp = 0;
    //int index = 0;
    
    
    for(int i = 0; i < n; i++){
        mean1 += arr[i];
        
        if(i > 0){
            temp = arr[i-1];
            
            if(temp == arr[i]){
                count++;
                if(count > first_max_same){
                    first_max_same = i;
                    
                }
                if((first_max_same > 1) && first_max_same == count){
                    second_max_same = i;
                }
            }
            else{
                count = 1;
            }
        }

감이 잡히지 않아 배열 두 개를 이용하여 구현한 파이썬으로 구현한 비슷한 예제를 찾아보면서 도전했지만

파이썬에서만 구현되는 기능으로 인해 쉽게 해결 되지 않았다.

[백준 2108번] 통계학 - 파이썬 (tistory.com)

 

[백준 2108번] 통계학 - 파이썬

문제 링크: https://www.acmicpc.net/problem/2108 2108번: 통계학 첫째 줄에 수의 개수 N(1 ≤ N ≤ 500,000)이 주어진다. 단, N은 홀수이다. 그 다음 N개의 줄에는 정수들이 주어진다. 입력되는 정수의 절댓값은 4

data-flower.tistory.com

 

// baekjoon 2107

#include<iostream>
#include<algorithm>
#include<cmath>

using namespace std;

// codes for fast I/O
void init(){
    cin.tie(0);
    cout.tie(0);
    ios_base::sync_with_stdio(false);
}


int main(){
    init();
    
    int n;
    cin >> n;
    
    int arr[n];
    
    for(int i = 0; i < n; i++){
        cin >> arr[i];
    }
    
    sort(arr, arr+n);
    
    // 산술 평균
    double mean1 = 0;
    
    
    // 최빈값
    int count = 1;
    int max_same_count = 1;
    int max_same_index = 0;
    int max_list[n];
    int temp = 0;
    
    
    for(int i = 1; i < n; i++){
        // 산술 평균
        mean1 += arr[i];
        
        // 최빈값
        temp = arr[i-1]; // 이전 인덱스 값 저장
            
        if(temp != arr[i]){
            if(count > max_same_count){
                max_list[n] = {};
                max_same_index = 0;
                max_list[max_same_index] = temp;
                max_same_count = count;
            }
            else if (count == max_same_count && temp != max_list[max_same_index]){
                max_same_index++;
                max_list[max_same_index] = temp;
            }
            count = 1;
            
        }
        
        else{
            count++;
        }
        
    }
    
    //int mean4 = 0;
    
    cout << int(round(double(mean1 / n))) << '\n';
    cout << arr[n/2] << '\n';
    if(max_list[1]>4000){
        cout << max_list[0] << '\n';
    }
    else{
        cout << max_list[1] << '\n';
    }
    cout << arr[n-1] - arr[0] << '\n';
    
}

stack을 사용하거나 다른 c++ 정답 처럼 8000 배열을 사용하여 다시 풀어야 할 것 같다.