작성일 :

문제 링크

11262번 - Minions’ Master

설명

마을 사람들의 전투력이 주어질 때, 평균 전투력과 평균보다 큰 사람의 비율을 구하는 문제입니다.


접근법

먼저 한 테스트케이스의 전투력 합을 구해 평균을 계산합니다.

그 다음 각 사람의 전투력이 평균보다 큰지 확인해서 인원을 셉니다. 마지막에는 평균과 비율을 모두 소수 셋째 자리까지 반올림해서 출력하면 됩니다.

반올림은 round half up 규칙을 따라야 하므로, C++에서는 정수 계산으로 소수 셋째 자리 값을 직접 만들어 출력하는 것이 안전합니다.



Code

C#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
using System;
using System.Globalization;

class Program {
  static void Main() {
    int t = int.Parse(Console.ReadLine()!);

    for (int tc = 0; tc < t; tc++) {
      string[] input = Console.ReadLine()!.Split();
      int n = int.Parse(input[0]);
      int[] power = new int[n];
      long sum = 0;

      for (int i = 0; i < n; i++) {
        power[i] = int.Parse(input[i + 1]);
        sum += power[i];
      }

      decimal average = (decimal)sum / n;
      int count = 0;
      for (int i = 0; i < n; i++) {
        if (power[i] > average)
          count++;
      }

      decimal roundedAverage = decimal.Round(average, 3, MidpointRounding.AwayFromZero);
      decimal percentage = (decimal)count * 100 / n;
      decimal roundedPercentage = decimal.Round(percentage, 3, MidpointRounding.AwayFromZero);

      Console.WriteLine(
        roundedAverage.ToString("0.000", CultureInfo.InvariantCulture) + " " +
        roundedPercentage.ToString("0.000", CultureInfo.InvariantCulture) + "%");
    }
  }
}

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <bits/stdc++.h>
using namespace std;

string formatScaled(long long scaled, bool withPercent) {
  long long integerPart = scaled / 1000;
  long long fractionalPart = scaled % 1000;

  string result = to_string(integerPart) + ".";
  if (fractionalPart < 100)
    result += "0";
  if (fractionalPart < 10)
    result += "0";
  result += to_string(fractionalPart);

  if (withPercent)
    result += "%";

  return result;
}

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

  int t;
  cin >> t;

  while (t--) {
    int n;
    cin >> n;

    vector<int> power(n);
    long long sum = 0;
    for (int i = 0; i < n; i++) {
      cin >> power[i];
      sum += power[i];
    }

    int count = 0;
    for (int i = 0; i < n; i++) {
      if ((long long)power[i] * n > sum)
        count++;
    }

    long long averageScaled = (sum * 1000 * 2 + n) / (2 * n);
    long long percentScaled = ((long long)count * 100000 * 2 + n) / (2 * n);

    cout << formatScaled(averageScaled, false) << " "
         << formatScaled(percentScaled, true) << "\n";
  }

  return 0;
}

Tags: 11262, BOJ, C#, C++, 구현, 백준, 수학, 알고리즘

Categories: ,