Weights and Scales
Time limit1sMemory limit128 MB
Place one gray weight on the empty pan, then repeatedly merge each balanced scale in the nested tower, and report the fewest weights that can remain.
- Level
Medium7 of 10
- Topics
- Prefix sum, Hash map
- Solved
- No attempts yet
Problem
Bajtek received a set of black weights, gray weights, and very light balance scales. Each scale has two pans.
He built one nested tower. He put the first scale on the floor. On one pan of it he placed the first black weight, and on the other pan he placed the second scale. On one pan of the second scale he placed the second black weight, and on its other pan the third scale, and so on. On the last, -th scale he placed the -th black weight on one pan and left the other pan empty.
Now for the puzzle. On the single empty pan you may place any one gray weight. Whenever some scale is in balance, meaning its two pans hold the same total mass, you may replace that whole scale together with everything resting on it by a single gray weight of the same total mass, as long as a gray weight of exactly that mass is still available. The scales themselves have negligible mass.
Bajtek wants the finished tower to hold as few weights as possible, so that he can easily mail it to his friend Bitoasia. Find the smallest number of weights that can remain in the tower.
Input
The first line contains one integer (), the number of scales.
The second line contains integers () separated by single spaces: the masses of the black weights, where sits on the scale on the floor and sits on a pan of the scale that carries .
The third line contains integers () separated by single spaces: the masses of the gray weights.
Output
Print one integer: the minimum number of weights that can remain in the tower.
Hint
