Last Updated: 4 Sep, 2025

Angler's Race

Hard
Asked in company
Samsung

Problem statement

There are 'N' fishing spots arranged in a line, numbered 1 to N. Three gates are located at specific spots, and at each gate, a number of fishermen are waiting.

The process of assigning fishermen to spots follows strict rules:

1) You must decide on an order to open the three gates.
2) A gate is opened, and all the fishermen from that gate must occupy the nearest available (unoccupied) fishing spots.
3) Only after all fishermen from the current gate are settled can the next gate in the chosen order be opened.

The distance a fisherman travels is the absolute difference between their gate's position and their assigned fishing spot's position. Your task is to find an optimal order for opening the gates that minimizes the total distance traveled by all fishermen combined.


Input Format:
The first line of input contains an integer 'N', the number of fishing spots.
The second line contains three space-separated integers, representing the positions of the three gates.
The third line contains three space-separated integers, representing the number of fishermen waiting at each corresponding gate.


Output Format:
Print a single integer representing the minimum possible total distance.


Note:
Since there are only 3 gates, there are only 3! = 6 possible orders to open them. The solution is to simulate the process for all 6 permutations and find the minimum total cost.
For each gate, the fishermen will greedily occupy the closest available spots.