Connection Status:
Competition Arena > OnTheFarmDivTwo
SRM 473 · 2009-11-12 · by misof · Brute Force, Simple Math
Class Name: OnTheFarmDivTwo
Return Type: int[]
Method Name: animals
Arg Types: (int, int)
Problem Statement

Problem Statement

There are some chickens and some cows in Farmer John's yard.

John's daughter Susie counted that all the animals in the yard have a total of 3 heads. John's son Billy counted their legs and got a total of 8. Using their answers, Farmer John easily determined that there have to be exactly 2 chickens and 1 cow.

Write a method that will solve a general version of Farmer John's problem. You are given two ints heads and legs. Compute the number of chickens and the number of cows. Return a int[] with two elements: first the number of chickens, then the number of cows. If there is no solution, return an empty int[] instead.

Notes

  • If the solution exists, it is always unique.
  • A chicken has 1 head and 2 legs. A cow has 1 head and 4 legs.

Constraints

  • heads will be between 0 and 1,000,000, inclusive.
  • legs will be between 0 and 1,000,000, inclusive.
Examples
0)
3
8
Returns: {2, 1 }

Two chickens and a cow have a total of three heads and eight legs.

1)
10
40
Returns: {0, 10 }

Ten cows.

2)
10
42
Returns: { }

This test case has no solution because the number of legs is too large (or the number of heads is too small).

3)
1
3
Returns: { }

No set of animals can have one head and three legs.

4)
0
0
Returns: {0, 0 }

Submissions are judged against all 143 archived test cases, of which 5 are shown here. Case numbers match the judge’s.

Coding Area

Language: C++17 · define a public class OnTheFarmDivTwo with a public method vector<int> animals(int heads, int legs) · 143 test cases · 2 s / 256 MB per case

Submitting as anonymous