작성일 :

문제 링크

24807번 - Math Homework

설명

세 종류 동물의 다리 수와 총 다리 수가 주어질 때, 총 다리 수를 만족하는 마릿수 조합을 모두 구하는 문제입니다.


접근법

첫 번째 동물 수를 0부터 가능한 최댓값까지, 두 번째 동물 수도 마찬가지로 순회합니다. 세 번째 동물 수는 남은 다리 수를 세 번째 동물의 다리 수로 나누어 계산하며, 나머지가 0인 경우만 유효한 조합입니다.

첫 번째 동물 수를 기준으로 오름차순 순회하므로 자연스럽게 사전순 출력이 됩니다. 유효한 조합이 없으면 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
23
24
25
26
27
28
29
using System;
using System.Collections.Generic;

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

    var ans = new List<(int x, int y, int z)>();
    for (var x = 0; x * b <= l; x++) {
      var remAfterX = l - x * b;
      for (var y = 0; y * d <= remAfterX; y++) {
        var rem = remAfterX - y * d;
        if (rem % c != 0) continue;
        var z = rem / c;
        ans.Add((x, y, z));
      }
    }

    if (ans.Count == 0) Console.WriteLine("impossible");
    else {
      foreach (var (x, y, z) in ans)
        Console.WriteLine($"{x} {y} {z}");
    }
  }
}

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
#include <bits/stdc++.h>
using namespace std;

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

  int b, d, c, l; cin >> b >> d >> c >> l;

  vector<tuple<int,int,int>> ans;
  for (int x = 0; x * b <= l; x++) {
    int remAfterX = l - x * b;
    for (int y = 0; y * d <= remAfterX; y++) {
      int rem = remAfterX - y * d;
      if (rem % c != 0) continue;
      int z = rem / c;
      ans.emplace_back(x, y, z);
    }
  }

  if (ans.empty()) cout << "impossible\n";
  else {
    for (auto [x, y, z] : ans)
      cout << x << " " << y << " " << z << "\n";
  }

  return 0;
}