#P8782. [蓝桥杯 2022 省 B] X 进制减法

[蓝桥杯 2022 省 B] X 进制减法

Background

2025-04-10: The incorrect testdata in the problem was removed.

Problem Description

A base determines when a carry happens on each digit position.

The XX base is a special kind of base, because the base of each digit position is not fixed. For example, for some XX-base number, the lowest digit position is base 22, the second digit position is base 1010, and the third digit position is base 88. Then the XX-base number 321 converts to the decimal number 65.

Now there are two integers AA and BB written in XX base, but the exact base of each digit position is still unknown. The only things known are that AA and BB follow the same base rule, and that for each digit position, the maximum base is N+1N+1 and the minimum base is 22. Please compute the minimum possible value of ABA-B.

Note that you must ensure that both AA and BB are valid in XX base, i.e., the digit on each position must be smaller than its base.

Input Format

The first line contains a positive integer NN, with the meaning as described above.

The second line contains a positive integer MaM_{a}, the number of digits of the XX-base number AA.

The third line contains MaM_{a} integers separated by spaces, representing the digits of AA in decimal, from the most significant digit to the least significant digit.

The fourth line contains a positive integer MbM_{b}, the number of digits of the XX-base number BB.

The fifth line contains MbM_{b} integers separated by spaces, representing the digits of BB in decimal, from the most significant digit to the least significant digit.

Note that all numbers in the input are in decimal.

Output Format

Output one line containing one integer, which is the minimum possible value of ABA-B in XX base, converted to decimal and then taken modulo 10000000071000000007 (i.e., 109+710^9+7).

11
3
10 4 0
3
1 2 0
94

Hint

Sample Explanation

When the bases are: base 22 for the lowest digit, base 55 for the second digit, and base 1111 for the third digit, the subtraction gives the minimum difference. In this case, AA is 108108 in decimal, BB is 1414 in decimal, and the difference is 9494.

Constraints and Notes

For 30%30\% of the data, N10N \leq 10, Ma,Mb8M_{a}, M_{b} \leq 8.

For 100%100\% of the data, 2N10002 \leq N \leq 1000, 1Ma,Mb1051 \leq M_{a}, M_{b} \leq 10^5, ABA \geq B.

Lanqiao Cup 2022 Provincial Contest B Group, Problem E.

Translated by ChatGPT 5