[BaekJoon 18110][⚪4] solved.ac

Date :   Updated :

❓ 문제

백준 18110 - “solved.ac”

🎯 난이도

Silver ⚪4

🧠 풀이

1. 내 풀이 (수학 + 정렬)

- 알고리즘

  • Mathematics, Sorting

- 설명

전형적인 수학 문제인데, 정렬을 곁들이는 풀이이다.

절삭값을 구하고, 평균을 구하는 과정은 적절한 캐스팅과 반올림을 위한 round 함수만 쓰면 된다. 거기에 더해서 정렬을 위한 sort를 쓰면 되는 간단한 문제이다.

floor(iN + 0.5f)식의 반올림 트릭도 존재하지만, 이는 해당값이 음수일 경우 적용되지 않으므로 보통은 'round' 함수를 쓰는 것이 안전하다.

sort 함수의 시간 복잡도가 전체 시간 복잡도이므로 O(N log N)이다.

- 코드

내 풀이 코드
#include <iostream>

#include <vector>

#include <algorithm>

#include <cmath>


using namespace std;

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int iN{};
    cin >> iN;

    if(iN == 0)
    {
        cout << 0;
        return 0;
    }
    
    vector<int> vecScore(iN);
    for(int& iScore : vecScore)
    {
        cin >> iScore;
    }
    
    sort(vecScore.begin(), vecScore.end());
    
    int iRound{ static_cast<int>(round(iN * 0.15f)) };  // 절삭값 구하기
    int iSum{};
    for(int i = iRound; i < iN - iRound; ++i)
    {
        iSum += vecScore[i];
    }

    // 캐스팅 주의할 것!!
    cout << static_cast<int>(round(iSum / static_cast<float>(iN - iRound * 2)));

    return 0;
}

💭 후기

이 문제에서 주의할 점은 제대로 된 반올림 계산과 캐스팅 밖에 없다. 캐스팅은 안전하게 static_cast를 쓰고, 반올림도 floor + 0.5f 트릭보단 round 함수를 써서 처리해 주도록 하자!

Comments