Its Sunday and it is a good idea to see what CodeForces have done through the week. As in general, lots of good problems. Thus, starting with the easiest one in the second division.
A monster is chasing after Rick and Morty on another planet. They’re so frightened that sometimes they scream. More accurately, Rick screams at times b, b + a, b + 2a, b + 3a, … and Morty screams at times d, d + c, d + 2c, d + 3c, ….
The Monster will catch them if at any point they scream at the same time, so it wants to know when it will catch them (the first time they scream at the same time) or that they will never scream at the same time.
The first line of input contains two integers a and b (1 ≤ a, b ≤ 100).
The second line contains two integers c and d (1 ≤ c, d ≤ 100).
Print the first time Rick and Morty will scream at the same time, or - 1 if they will never scream at the same time.
The trick here is to realize, that the numbers are pretty small and that they cannot repeat per runner. Furthermore, they are only increasing. E.g. Rick cannot shout twice in the same second and the fifth time he screams is always before the sixth time he screams. Thus, if you start writing down the scream times down for our two heroes, the first time you see equal numbers would be automatically the first time they scream together.
Thus, simply add the times they scream into a dictionary as a key (a list is also possible) and check if the list contains a key. If the answer is yes – then the other hero has screamed at this time already and thus this is the answer.
Enjoy the code:
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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Monsters { static void Main() { List<int> pesho = Console.ReadLine().Split().Select(int.Parse).ToList(); List<int> gosho = Console.ReadLine().Split().Select(int.Parse).ToList(); int a = pesho[0]; int b = pesho[1]; int c = gosho[0]; int d = gosho[1]; int peshoC; int goshoC; Dictionary<int, int=""> screamers = new Dictionary<int, int="">(); int MaxTime = (int)Math.Pow(100,2)+1; int Result = -1; for (int i = 0; i < MaxTime; i++) { peshoC = b + a * i; goshoC = d + c * i; if (!screamers.ContainsKey(peshoC)) { screamers.Add(peshoC, 1); } else { Result = peshoC; break; } if (!screamers.ContainsKey(goshoC)) { screamers.Add(goshoC, 1); } else { Result = goshoC; break; } } Console.WriteLine(Result); } } |
🙂