Under construction

Still being built. Things may change

Flooding Wall

Time limit5sMemory limit1024 MB

Summary
Each of N wall segments has one of two candidate heights, so sum the water trapped over all 2^N walls, modulo 1e9+7.
Level

Medium7 of 10

Topics
Sorting, Prefix sum, Math
Solved
No attempts yet

Problem

It's the 14th century and construction of the Trakai Island Castle is to begin soon. The first task on the chief architect's list is to plan the construction of the main castle wall.

Building a wall that can protect the castle from any possible attack is quite tricky. To ensure the safety of the castle garrison, the chief architect has already narrowed the design space somewhat.

Attacks from the middle of the lake are less likely than attacks from the nearby shore, so the wall does not need to form a closed loop. Instead, it is a straight line of NN segments arranged from one end to the other and numbered 11 to NN. What remains is to pick the height of each segment.

The chief architect has already picked two possible heights for each segment. The height of the ii-th segment is either aia_i or bib_i. That leaves 2N2^N possibilities.

A castle on a small island in a lake has its difficulties. During stormy weather, the castle can get flooded. Water collects above a wall segment when there are higher segments on both sides of it, and it cannot drain.

Input

The first line contains one integer NN.

The second line contains NN integers a1,a2,…,aNa_1, a_2, \dots, a_N.

The third line contains NN integers b1,b2,…,bNb_1, b_2, \dots, b_N.

Output

Print a single integer: the sum of the total water collected over all 2N2^N possible walls, modulo 109+710^9 + 7.

For a fixed choice of heights, the water level at position ii is at least hh if and only if there exist integers l≤i≤rl \le i \le r such that the heights at positions ll and rr are both at least hh. The water level at positions 11 and NN always equals their segment heights, and the water level at any position is at least the height of its segment. The water collected at position ii is the water level minus the segment height, and the total is the sum over positions 1,2,…,N1, 2, \dots, N.

Constraints

1≤N≤5⋅1051 \le N \le 5 \cdot 10^5.

1≤ai,bi≤1091 \le a_i, b_i \le 10^9 and ai≠bia_i \ne b_i for all 1≤i≤N1 \le i \le N.

Examples2

  1. Example 1

    Input
    4
    1 1 1 1
    2 2 2 2
    
    Expected output
    6
    
  2. Example 2

    Input
    10
    1 2 3 4 5 6 7 8 9 10
    10 9 8 7 6 5 4 3 2 1
    
    Expected output
    21116