작성일 :

문제 링크

26941번 - Pyramidbygge

설명

한 층의 한 변 길이가 2씩 줄어드는 정사각형 층으로 피라미드를 만들 때, 사용할 수 있는 블록 수로 만들 수 있는 최대 높이를 구하는 문제입니다.


접근법

각 층은 한 변이 1, 3, 5, … 인 정사각형이므로 필요한 블록 수는 홀수 제곱의 누적 합입니다. 다음 층을 추가할 수 있을 때까지 높이를 증가시키면 됩니다.


Code

C#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System;

class Program {
  static void Main() {
    var n = int.Parse(Console.ReadLine()!);
    var total = 0;
    var h = 0;

    while (true) {
      var side = 2 * h + 1;
      var need = side * side;
      if (total + need > n) break;
      total += need;
      h++;
    }

    Console.WriteLine(h);
  }
}

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <bits/stdc++.h>
using namespace std;

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

  int n; cin >> n;
  int total = 0;
  int h = 0;

  while (true) {
    int side = 2 * h + 1;
    int need = side * side;
    if (total + need > n) break;
    total += need;
    h++;
  }

  cout << h << "\n";

  return 0;
}