[백준 16283] Farm (C#, C++) - soo:bak
작성일 :
문제 링크
설명
총 마리 수와 사료 소비량이 주어졌을 때 양과 염소의 수를 구하는 문제입니다.
접근법
양의 수를 x라 두면 염소의 수는 n-x입니다.
a*x + b*(n-x) = w를 만족하는 x를 모두 확인해 해가 유일한지 판단합니다.
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
using System;
class Program {
static void Main() {
var parts = Console.ReadLine()!.Split();
var a = int.Parse(parts[0]);
var b = int.Parse(parts[1]);
var n = int.Parse(parts[2]);
var w = int.Parse(parts[3]);
var found = 0;
var sheep = 0;
var goat = 0;
for (var x = 1; x <= n - 1; x++) {
var y = n - x;
if (a * x + b * y == w) {
found++;
sheep = x;
goat = y;
}
}
if (found == 1) Console.WriteLine($"{sheep} {goat}");
else Console.WriteLine(-1);
}
}
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
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int a, b, n, w; cin >> a >> b >> n >> w;
int found = 0, sheep = 0, goat = 0;
for (int x = 1; x <= n - 1; x++) {
int y = n - x;
if (a * x + b * y == w) {
found++;
sheep = x;
goat = y;
}
}
if (found == 1) cout << sheep << " " << goat << "\n";
else cout << -1 << "\n";
return 0;
}