#P2693. Farmer John's Combination Lock

    ID: 15958 Type: Default 1000ms 256MiB

Farmer John's Combination Lock

Farmer John's Combination Lock

Farmer John's cows keep escaping from his farm, causing much damage. To prevent them from getting out, he buys a large combination lock to keep the cows from opening the barn door. The lock has three circular dials, each showing numbers from 1 to n. Because the dials are circular, the numbers 1 and n are adjacent.

There are two valid combinations that open the lock. One is the combination chosen by Farmer John and the other is a "preset" combination set by the locksmith. However, the lock is "forgiving": it will open if, for either valid combination, every dial of the lock is set to a number that is at most 2 positions away (in the circular sense) from the corresponding number in that valid combination.

For example, suppose Farmer John's combination is \( (1,2,3) \) and the preset combination is \( (4,5,6) \). Then the lock will open for the setting \( (1,4,5) \) because each digit is within 2 positions of the corresponding digit in Farmer John's combination, and it will also open for \( (2,4,8) \) because each digit is within 2 positions of the corresponding digit in the preset combination. Note that \( (1,5,6) \) does not open the lock, since it is not close enough to either valid combination.

Given the two valid combinations, compute the number of distinct dial settings that will open the lock. Two settings are considered different if the order of the numbers is different.

The circular distance between two numbers \( a \) and \( b \) on a dial of size \( n \) is defined as:

[ \min(|a-b|, n-|a-b|) \le 2. ]

</p>

inputFormat

The input consists of three lines:

  • The first line contains an integer \( n \) (\( n \ge 1 \)), the maximum number on the dials.
  • The second line contains three integers representing Farmer John's combination.
  • The third line contains three integers representing the preset combination.

outputFormat

Output a single integer, the number of distinct dial settings that will open the lock.

sample

50
1 2 3
5 6 7
249