본문 바로가기
알고리즘/백준 BOJ

[ BOJ/C# ] 2108 통계학

by 왹져박사 2023. 10. 27.
728x90

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

 

2108번: 통계학

첫째 줄에 수의 개수 N(1 ≤ N ≤ 500,000)이 주어진다. 단, N은 홀수이다. 그 다음 N개의 줄에는 정수들이 주어진다. 입력되는 정수의 절댓값은 4,000을 넘지 않는다.

www.acmicpc.net

중앙값과 최빈값에 대하여 좀 생각해야 하는 문제였다. 

중앙값은 n이 짝수일 경우를 생각해야 했고, 

최빈값은 최빈값이 여러 개 있을 경우 두 번째로 작은 값을 출력해야 했다. 

이를 위해 값의 수를 세는 배열을 따로 만들어 구해주었다!

using System;
using System.IO;
using System.Text;

namespace B2108
{
    class Program
    {
        static void Main()
        {
            StreamReader sr = new StreamReader(Console.OpenStandardInput());
            StreamWriter sw = new StreamWriter(Console.OpenStandardOutput());
            StringBuilder sb = new StringBuilder();

            int n = int.Parse(sr.ReadLine());
            List<double> list = new List<double>();
            int[] ints = new int[8001];
            for (int i = 0; i < n; i++)
            {
                int input = int.Parse(sr.ReadLine());
                list.Add(input);
                ints[input + 4000]++;
            }
            list.Sort();    //정렬

            //산술평균
            int a = Convert.ToInt32(list.Average());
            sb.Append(a + "\n");

            //중앙값
            if (n % 2 == 0)
            {
                double mid = (list[n / 2] + list[n / 2 - 1]) / 2;
                sb.Append(mid + "\n");
            }
            else sb.Append(list[n / 2] + "\n");

            //최빈값
            int max = ints.Max();
            List<int> listM = new List<int>();
            for(int i = 0; i < 8001; i++)
            {
                if (ints[i] == max) listM.Add(i - 4000);
            }
            if (listM.Count > 1) sb.Append(listM[1] + "\n");
            else sb.Append(listM[0] + "\n");
            
            //범위
            sb.Append((list.Max() - list.Min()) + "\n");

            sw.Write(sb);
            sr.Close();
            sw.Flush();
            sw.Close();
        }
    }
}

728x90

'알고리즘 > 백준 BOJ' 카테고리의 다른 글

[ BOJ/C# ] 4949 균형잡힌 세상  (0) 2023.10.29
[ BOJ/C# ] 11050 이항 계수 1  (1) 2023.10.28
[ BOJ/C# ] 18110 solved.ac  (0) 2023.10.25
[ BOJ/C# ] 16928 뱀과 사다리 게임  (0) 2023.10.24
[ BOJ/C# ] 1697 숨바꼭질  (0) 2023.10.24