작성일 :

문제 링크

3602번 - iChess

설명

흑백 타일 개수가 주어질 때 체스판 무늬가 되는 정사각형의 최대 한 변 길이를 구하는 문제입니다.


접근법

한 변이 s인 정사각형은 전체 칸 수가 s의 제곱이고, 두 색의 개수 차는 많아야 1입니다.
따라서 절반과 그보다 1 큰 수의 조합이 흑백 타일 개수 안에 들어가면 만들 수 있습니다.
가능한 최대 변 길이부터 내려가며 확인하고, 없으면 Impossible을 출력합니다.


Code

C#

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

class Program {
  static void Main() {
    var parts = Console.ReadLine()!.Split();
    var b = int.Parse(parts[0]);
    var w = int.Parse(parts[1]);

    var maxSide = (int)Math.Sqrt(b + w);
    for (var s = maxSide; s >= 1; s--) {
      var total = s * s;
      var a = total / 2;
      var bNeed = total - a;
      if ((b >= bNeed && w >= a) || (b >= a && w >= bNeed)) {
        Console.WriteLine(s);
        return;
      }
    }

    Console.WriteLine("Impossible");
  }
}

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 b, w; cin >> b >> w;
  int maxSide = (int)sqrt(b + w);
  for (int s = maxSide; s >= 1; s--) {
    int total = s * s;
    int a = total / 2;
    int bNeed = total - a;
    if ((b >= bNeed && w >= a) || (b >= a && w >= bNeed)) {
      cout << s << "\n";
      return 0;
    }
  }

  cout << "Impossible\n";

  return 0;
}