작성일 :

문제 링크

9806번 - The King

설명

문제의 목표는 왕이 장군으로 선발할 아들들의 잠재력에 대한 거듭제곱 합이 최대가 되도록 하여,

야만인들과의 전투에서 승리할 확률의 최댓값을 구하는 것입니다.

만약, 잠재력이 음수이면서 지수가 홀수일 때는 승리할 확률에 부정적인 영향을 미칠수 있다는 점에 주의해야 합니다.

풀이 과정은 다음과 같습니다.

  • 아들들의 정신력을 입력받고, 이를 양수와 음수로 분류합니다.
  • 양수는 큰 순서대로, 음수는 절대값이 큰 순서대로 정렬합니다.
  • 입력으로 주어진 지수를 적용하여 양수들의 거듭제곱 합을 구합니다.
  • 지수가 짝수일 경우, 음수에 대해서도 지수를 적용하여 음수들의 거듭제곱 합을 구하여 합산합니다.
  • 최종적으로 합산된 값이 왕국을 지키기 위한 최대 가능성이 됩니다.

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
namespace Solution {
  class Program {
    static void Main(string[] args) {

      var cntSons = int.Parse(Console.ReadLine()!);
      var exponent = int.Parse(Console.ReadLine()!);

      List<int> posPotential = new List<int>();
      List<int> negPotential = new List<int>();
      var potentials = Console.ReadLine()!.Split(' ').Select(int.Parse).ToArray();
      for (int i = 0; i < cntSons; i++) {
        if (potentials[i] > 0) posPotential.Add(potentials[i]);
        else negPotential.Add(potentials[i]);
      }

      posPotential.Sort((a, b) => b.CompareTo(a));
      negPotential.Sort((a, b) => Math.Abs(b).CompareTo(Math.Abs(a)));

      int maxChanceWin = 0;
      foreach (var potential in posPotential)
        maxChanceWin += (int)Math.Pow(potential, exponent);

      if (exponent % 2 == 0) {
        foreach (var potentail in negPotential)
          maxChanceWin += (int)Math.Pow(potentail, exponent);
      }

      Console.WriteLine(maxChanceWin);

    }
  }
}



[ 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
#include <bits/stdc++.h>

using namespace std;

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

  int cntSons, exponent; cin >> cntSons >> exponent;

  vector<int> posPotential, negPotential;
  for (int i = 0; i < cntSons; i++) {
    int potential; cin >> potential;
    if (potential > 0) posPotential.push_back(potential);
    else negPotential.push_back(potential);
  }

  sort(posPotential.rbegin(), posPotential.rend());
  sort(negPotential.begin(), negPotential.end(), [](const int& a, const int& b) { return abs(a) > abs(b); });

  int maxChanceWin = 0;
  for (const auto& potential : posPotential)
    maxChanceWin += pow(potential, exponent);

  if (exponent % 2 == 0) {
    for (const auto& potential : negPotential)
      maxChanceWin += pow(potential, exponent);
  }

  cout << maxChanceWin << "\n";

  return 0;
}