P15772 [JAG 2025 Summer Camp #2] Driving Playlist
Description
You are going to go driving with $m$ friends. To enjoy the driving, you have a playlist of $n$ songs numbered $1$ through $n$.
At time $0$ you choose one of the songs and start it from its beginning. Then, the playlist repeats forever. For each $k$ ($1 \leq k \leq n$), once the song $k$ starts, it lasts $l_k$ units of of time, and then the song $k+1$ (or the song $1$ if $k=n$) follows immediately.
The $i$-th friend, who loves the song $f_i$, joins you at time $t_i - 0.5$. After that, they get excited whenever the song $f_i$ starts. Note that even if the song $f_i$ is already being played when they join you, they don't get excited because everyone wants to enjoy their favorite song from the beginning.
If you choose the first song to play optimally, when is the earliest time that all the $m$ friends get excited at least once? Note that you cannot start playing a song from the middle.
Input Format
The input consists of a single test case of the following format.
$$
\begin{aligned}
& n \ m \\
& l_1 \ l_2 \ \cdots \ l_n \\
& t_1 \ t_2 \ \cdots \ t_m \\
& f_1 \ f_2 \ \cdots \ f_m
\end{aligned}
$$
The first line contains two integers $n$ and $m$ ($1 \leq n \leq 200\,000$, $1 \leq m \leq 200\,000$). $n$ is the number of songs in the playlist and $m$ is the number of friends who join your driving.
The second line contains $n$ positive integers $l_1, l_2, \ldots, l_n$. Each $l_i$ represents the length of the song $i$. Their sum does not exceed $10^{15}$.
The third line contains $m$ integers $t_1, t_2, \ldots, t_m$ ($1 \leq t_i \leq 10^{15}$). Each $t_i$ represents that the $i$-th friend joins you at time $t_i - 0.5$.
The fourth line contains $m$ integers $f_1, f_2, \ldots, f_m$ ($1 \leq f_i \leq n$). Each $f_i$ is the number of the favorite song of the $i$-th friend.
Output Format
Output an integer, which is the earliest time that all the $m$ friends get excited at least once.
Explanation/Hint
In the first sample, if you start the playlist from song $3$, the four friends first get excited at times $12$, $8$, $7$, and $12$, respectively.