Problem:


Score : 400 points

Problem Statement

Mountaineers Mr. Takahashi and Mr. Aoki recently trekked across a certain famous mountain range.
The mountain range consists of N mountains, extending from west to east in a straight line as Mt. 1, Mt. 2, ..., Mt. N.
Mr. Takahashi traversed the range from the west and Mr. Aoki from the east.  

The height of Mt. i is h_i, but they have forgotten the value of each h_i.
Instead, for each i (1 ≤ i ≤ N), they recorded the maximum height of the mountains climbed up to the time they reached the peak of Mt. i (including Mt. i).
Mr. Takahashi's record is T_i and Mr. Aoki's record is A_i.  

We know that the height of each mountain h_i is a positive integer.
Compute the number of the possible sequences of the mountains' heights, modulo 10^9 + 7.

Note that the records may be incorrect and thus there may be no possible sequence of the mountains' heights.
In such a case, output 0.

Constraints

1 ≤ N ≤ 10^5

1 ≤ T_i ≤ 10^9

1 ≤ A_i ≤ 10^9

T_i ≤ T_{i+1} (1 ≤ i ≤ N - 1)

A_i ≥ A_{i+1} (1 ≤ i ≤ N - 1)

Input

The input is given from Standard Input in the following format:

N
T_1 T_2 ... T_N
A_1 A_2 ... A_N

Output

Print the number of possible sequences of the mountains' heights, modulo 10^9 + 7.

Sample Input 1

5
1 3 3 3 3
3 3 2 2 2

Sample Output 1

4

The possible sequences of the mountains' heights are:

1, 3, 2, 2, 2 

1, 3, 2, 1, 2 

1, 3, 1, 2, 2 

1, 3, 1, 1, 2 

for a total of four sequences.

Sample Input 2

5
1 1 1 2 2
3 2 1 1 1

Sample Output 2

0

The records are contradictory, since Mr. Takahashi recorded 2 as the highest peak after climbing all the mountains but Mr. Aoki recorded 3.

Sample Input 3

10
1 3776 3776 8848 8848 8848 8848 8848 8848 8848
8848 8848 8848 8848 8848 8848 8848 8848 3776 5

Sample Output 3

884111967

Don't forget to compute the number modulo 10^9 + 7.

Sample Input 4

1
17
17

Sample Output 4

1

Some mountain ranges consist of only one mountain.



Sample input:
5
1 3 3 3 3
3 3 2 2 2


Sample output:
4

Submission status: Accepted

Solution code:
n = int(input())
a = [int(i) for i in input().split()]
b = [int(i) for i in input().split()]

is_ok_a = [False] * n
max_a = [0]*n
pre = -1
for i, j in enumerate(a):
    if j != pre:
        pre = j
        is_ok_a[i] = True
    max_a[i] = pre

is_ok_b = [False] * n
max_b = [0]*n
pre = -1
for i, j in reversed(list(enumerate(b))):
    if j != pre:
        pre = j
        is_ok_b[i] = True
    max_b[i] = pre
mod = 10**9+7
ans = 1
for i in range(n):
    if is_ok_a[i] and is_ok_b[i]:
        if max_a[i] == max_b[i]:
            ans *= 1
        else:
            ans *= 0
    elif is_ok_a[i]:
        if max_a[i] <= max_b[i]:
            ans *= 1
        else:
            ans *= 0
    elif is_ok_b[i]:
        if max_a[i] >= max_b[i]:
            ans *= 1
        else:
            ans *= 0
    else:
        ans *= min(max_a[i], max_b[i])
    ans %= mod
print(ans)

Submission status: Accepted

Solution code:
import sys

input_methods=['clipboard','file','key']
using_method=0
input_method=input_methods[using_method]

IN=lambda : map(int, input().split())
mod=1000000007

#+++++

def main():
	n = int(input())
	al = list(IN())
	bl=list(IN())
	mm=[]
	for i in range(n):
		mm.append([0,0])
	im=0
	for i, h in enumerate(al):
		if im < h:
			mm[i] = [h,h]
			im=h
		else:
			mm[i] = [1,h]
	jm=0
	for i, h in enumerate(bl[::-1]):
		j=n-i-1
		if jm < h:
			if mm[j][0]<= h and h <= mm[j][1]:
				mm[j] = [h,h]
				jm=h
			else:
				return 0
		else:
			if mm[j][0]<= h and h <= mm[j][1]:
				mm[j][1]=h
			elif h < mm[j][0]:
				return 0
			else:
				pass
	r=1
	for a,b in mm:
		r *= (b-a+1)
		r %= mod
	print(r)
		
	
	
	
#+++++
isTest=False

def pa(v):
	if isTest:
		print(v)
		
def input_clipboard():
	import clipboard
	input_text=clipboard.get()
	input_l=input_text.splitlines()
	for l in input_l:
		yield l

if __name__ == "__main__":
	if sys.platform =='ios':
		if input_method==input_methods[0]:
			ic=input_clipboard()
			input = lambda : ic.__next__()
		elif input_method==input_methods[1]:
			sys.stdin=open('inputFile.txt')
		else:
			pass
		isTest=True
	else:
		pass
		#input = sys.stdin.readline
			
	ret = main()
	if ret is not None:
		print(ret)

Submission status: Accepted

Solution code:
"""from collections import *
from itertools import *
from bisect import *
from heapq import *

import math
from fractions import gcd"""

N=int(input())
T=list(map(int,input().split()))
A=list(map(int,input().split()))
mod=10**9+7
lst=[0 for i in range(N)]


lst[0]=T[0]
lst[N-1]=A[N-1]
if T[N-1]!=A[0]:
    print(0)
    exit()
for i in range(1,N):
    if T[i]>T[i-1]:
        if lst[i] and lst[i]!=T[i]:
            print(0)
            exit()
        lst[i]=T[i]

for i in range(N-2,-1,-1):
    if A[i]>A[i+1]:
        if lst[i] and lst[i]!=A[i]:
            print(0)
            exit()
        elif not lst[i] and T[i]<A[i]:
            print(0)
            exit()
        lst[i]=A[i]

count=1
for i in range(N):
    if not lst[i]:
        count=count*min(T[i],A[i])%mod
print(count)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.buffer.readline
from operator import itemgetter

def main():
    N = int(input())
    
    t = list(map(int,input().split()))
    a = list(map(int,input().split()))
    MOD = 10**9+7
    
    tt,tl = 0,[False for _ in range(N)]
    for x,num in enumerate(t):
        if num > tt:
            tl[x] = True
            tt = num
            
    at,al = 0,[False for _ in range(N)]
    for x,num in enumerate(a[::-1]):
        if num > at:
            al[-x-1] = True
            at = num

    ans,now = 1,0
    for i in range(N):
        if tl[i] == True and al[i] == True:
            if now < t[i] == a[i]:
                now = a[i]
            else:
                print(0)
                exit()
        elif tl[i] == True and al[i] == False:
            if t[i] > a[i]:
                print(0)
                exit()
            else:
                now = t[i]
        elif tl[i] == False and al[i] == True:
            if t[i] < a[i]:
                print(0)
                exit()
            else:
                now = a[i]
        else:
            ans *= min(t[i],a[i])
            ans %= MOD
    
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

N = int(input())
T = list(map(int, input().split()))
A = list(map(int, input().split()))
maxh = [0] * N
if T[0] > A[0] or T[-1] < A[-1]:
    print(0)
    exit()

maxh[0] = -T[0]
for i in range(1, N):
    if T[i-1] == T[i]:
        maxh[i] = T[i]
    else:
        maxh[i] = -T[i]

maxh[-1] = -A[-1]
for i in range(N-1)[::-1]:
    if maxh[i] > 0:
        if A[i] == A[i+1]:
            maxh[i] = min(maxh[i], A[i])
        else:
            if maxh[i] < A[i]:
                print(0)
                exit()
            else:
                maxh[i] = -A[i]
    else:
        if A[i] == A[i+1]:
            if -maxh[i] > A[i]:
                print(0)
                exit()
        else:
            if -maxh[i] != A[i]:
                print(0)
                exit()

ans = 1
mod = 10**9+7
for i in range(N):
    if maxh[i] > 0:
        ans = ans * maxh[i] % mod
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
t = list(map(int, input().split()))
a = list(map(int, input().split()))
mod = 10**9 + 7
#どちらかの値が切り替わってるところは、1通りしかなく、そこが矛盾している場合は弾く
h = [-1 for i in range(n)]
t = [0] + t
a += [0]
for i in range(n):
    if t[i+1] != t[i]:
        h[i] = t[i+1]
for i in range(n,0,-1):
    if h[i-1] != -1 and h[i-1] > a[i-1]:
        print(0)
        exit()
    if a[i] != a[i-1]:
        if h[i-1] == -1:
            h[i-1] = a[i-1]
        else:
            if h[i-1] != a[i-1]:
                print(0)
                exit()
ans = 1
for i in range(n):
    if h[i] == -1:
        #print("index:{} t:{} a:{}".format(i,t[i+1], a[i]))
        ans *= min(t[i+1], a[i])
        ans %= mod
print(ans)

Submission status: Accepted

Solution code:
import sys

def solve():
    input = sys.stdin.readline
    N = int(input())
    T = [int(t) for t in input().split()]
    A = [int(a) for a in input().split()]
    mod = 7 + 10 ** 9
    Ans = 1
    H = [-1] * N
    H[0] = T[0]
    for i in range(1, N):
        if T[i] > T[i-1]: H[i] = T[i]
    if H[N-1] > -1 and H[N-1] != A[N-1]: Ans = 0
    else: H[N-1] = A[N-1]
    for i in reversed(range(N-1)):
        if A[i] > A[i+1]:
            if H[i] > -1 and H[i] != A[i]: Ans = 0
            elif T[i] < A[i]: Ans = 0
            else: H[i] = A[i]
        else:
            if H[i] == -1: 
                Ans *= min(T[i], A[i])
                Ans %= mod
    print(Ans)
            
    return 0

if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
def main():
    MOD = 10**9 + 7
    N = int(input())
    T = [int(i) for i in input().split()]
    A = [int(i) for i in input().split()]
    if T[-1] != A[0]:
        return print(0)
    ma_idx_T = T.index(max(T))
    # print(ma_idx_T)
    if A[ma_idx_T] != T[ma_idx_T]:
        return print(0)
    non_fix = [True] * N
    non_fix[0] = False
    non_fix[-1] = False
    for i in range(1, N):
        if T[i-1] < T[i]:
            non_fix[i] = False
            ma_idx_T = i
        else:
            continue

    for i in range(N-1)[::-1]:
        if A[i] > A[i+1]:
            non_fix[i] = False
        else:
            continue
    ans = 1
    # print(non_fix)
    for i, f in enumerate(non_fix):
        if f:
            ans *= min(T[i], A[i])
            ans %= MOD
    print(ans % MOD)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def examA():
    N = I()
    T = LI()
    A = LI()
    S = [-1]*N
    S[0] = T[0]; S[-1]=A[-1]
    ans = 1
    for i in range(1,N):
        if T[i]==T[i-1]:
            continue
        S[i] = T[i]
    flag = -1
    for i in range(N):
        if S[i]==A[i]:
            flag = i
            break
    if not (A[flag]==A[0] and A[flag]==T[-1]):
        print(0)
        return
    for i in range(N-1)[::-1]:
        if A[i]==A[i+1]:
            continue
        if S[i]==-1:
            S[i] = A[i]
        else:
            S[i] = max(S[i],A[i])
    #print(S)
    P = []
    pindex = []
    for i in range(N):
        if S[i]==-1:
            continue
        P.append(S[i])
        pindex.append(i)
    flag_U = True
    for i in range(len(P)-1):
        if P[i+1]>P[i]:
            if not flag_U:
                print(0)
                return
        elif P[i+1]<P[i]:
            flag_U = False
    ans = 1
    p = -1
    for i in range(N):
        if S[i]==-1:
            cur = min(P[p + 1], P[p])
            ans *= cur
            ans %= mod
        else:
            p += 1

    print(ans)
    return

def examB():
    ans = 0
    print(ans)
    return

def examC():
    ans = 0
    print(ans)
    return

def examD():
    ans = 0
    print(ans)
    return

import sys,copy,bisect,itertools,heapq,math,random
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = 10**(-12)
alphabet = [chr(ord('a') + i) for i in range(26)]

if __name__ == '__main__':
    examA()

"""

"""

Submission status: Accepted

Solution code:
N = int(input())
T = list(map(int, input().split()))
A = list(map(int, input().split()))

H = [[-1, 10**9] for i in range(N)]

prev = 0
for i, x in enumerate(T):
    if prev != x:
        if H[i][0] < 0:
            H[i][0] = x
        elif H[i][0] != x:
            print(0)
            exit(0)
    prev = x
    H[i][1] = min(H[i][1], x)
prev = 0
for i in range(N-1, -1, -1):
    x = A[i]
    if prev != x:
        if H[i][0] < 0:
            if H[i][1] >= x:
                H[i][0] = x
            else:
                print(0)
                exit(0)
        elif H[i][0] != x:
            print(0)
            exit(0)
    prev = x
    H[i][1] = min(H[i][1], x)
ans = 1
mod = 10**9 + 7
for x, y in H:
    if x > 0:
        continue
    else:
        ans *= y
        ans %= mod
print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
N = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
mod = 10 ** 9 + 7
t = [10 ** 10 for _ in range(N)]
t[0] = a[0]
t[-1] = b[-1]
s = set()
s.add(0)
s.add(N - 1)
if a[0] > b[0] or (a[-1] < b[-1]):
  print(0)
  exit(0)
if a[-1] != b[0]:
  print(0)
  exit(0)
for i in range(N - 1):
  if a[i + 1] > a[i]:
    if t[i + 1] > 0 and (t[i + 1] in range(a[i + 1])):
      print(0)
      exit(0)
    s.add(i + 1)
    t[i + 1] = a[i + 1]
  else: t[i + 1] = min(t[i + 1], t[i])
#print(t)
for i in range(N - 1, 0, -1):
  if b[i - 1] > b[i]:
    if t[i - 1] > 0 and (t[i - 1] in range(b[i - 1])):
      print(0)
      exit(0)
    s.add(i - 1)
    t[i - 1] = b[i - 1]
  else: t[i - 1] = min(t[i - 1], t[i])
#print(t)
res = 1
for i in range(N):
  if i in s: continue
  res *= t[i]
  res %= mod
print(res)

Submission status: Accepted

Solution code:
N = int(input())
T = list(map(int, input().split()))
A = list(map(int, input().split()))

class Mint:
    @staticmethod
    def get_value(x): return x.value if isinstance(x, Mint) else x

    def __init__(self, val, mod=10**9+7):
        val = Mint.get_value(val)
        self.__mod = mod
        self.__val = val % self.__mod

    @property
    def value(self): return self.__val
    @property
    def inverse(self): return pow(self.__val, self.__mod - 2, self.__mod)

    def __eq__(self, other): return self.__val == other.val
    def __ne__(self, other): return self.__val != other.val

    def __neg__(self): return Mint(self.__val, self.__mod)

    def __iadd__(self, other):
        other = Mint.get_value(other)
        self.__val = (self.__val + other) % self.__mod
        return self
    def __add__(self, other):
        new = Mint(self.__value, self.__mod)
        new += other
        return new
    def __radd__(self, other): return self + other

    def __isub__(self, other):
        other = Mint.get_value(other)
        self.__val = (self.__val - other + self.__mod) % self.__mod
        return self
    def __sub__(self, other):
        new = Mint(self.__value, self.__mod)
        new -= other
        return new
    def __rsub__(self, other):
        new = Mint(Mint.get_value(other), self.__mod)
        new -= self
        return new

    def __imul__(self, other):
        other = Mint.get_value(other)
        self.__val = self.__val * other % self.__mod
        return self
    def __mul__(self, other):
        new = Mint(self.__value, self.__mod)
        new *= other
        return new
    def __rmul__(self, other): return self * other

    def __ifloordiv__(self, other):
        other = Mint(other, self.__mod)
        self *= other.inverse
        return self
    def __floordiv__(self, other):
        new = Mint(self.__value, self.__mod)
        new //= other
        return new
    def __rfloordiv__(self, other):
        new = Mint(Mint.get_value(other), self.__mod)
        new //= self
        return new

if T[N-1] != A[0]:
    print(0)
    exit()

ans = Mint(1)
for i in range(N):
    if i==0 or i==N-1: continue
    if T[i-1] != T[i]:
        if T[i] == A[0] and A[i] != A[0]:
            print(0)
            exit()
        continue
    if A[i] != A[i+1]:
        if A[i] == A[0] and T[i] != A[0]:
            print(0)
            exit()
        continue
    ans *= min(T[i], A[i])
print(ans.value)

Submission status: Accepted

Solution code:
import sys
import math
from collections import defaultdict

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def LI(): return list(map(int, input().split()))
def LIR(row,col):
    if row <= 0:
        return [[] for _ in range(col)]
    elif col == 1:
        return [I() for _ in range(row)]
    else:
        read_all = [LI() for _ in range(row)]
        return map(list, zip(*read_all))

#################

N = I()
T = LI()
A = LI()

if T[0] > A[0]:
    print(0)
    exit()

if T[N-1] < A[N-1]:
    print(0)
    exit()

ans = 1
for i in range(1,N-1):
    if T[i-1] != T[i]:
        if A[i] < T[i]:
            print(0)
            exit()
        else:
            continue
    else:
        if A[i+1] != A[i]:
            if T[i] < A[i]:
                print(0)
                exit()
            else:
                continue
        else:
            ans *= min(A[i],T[i])
            ans %= mod

print(ans)

Submission status: Accepted

Solution code:
MOD=10**9+7
class Fp(int):
    def __new__(self,x=0):return super().__new__(self,x%MOD)
    def inv(self):return self.__class__(super().__pow__(MOD-2,MOD))
    def __add__(self,value):return self.__class__(super().__add__(value))
    def __sub__(self,value):return self.__class__(super().__sub__(value))
    def __mul__(self,value):return self.__class__(super().__mul__(value))
    def __floordiv__(self,value):return self.__class__(self*self.__class__(value).inv())
    def __pow__(self,value):return self.__class__(super().__pow__(value%(MOD-1), MOD))
    __radd__=__add__
    __rmul__=__mul__
    def __rsub__(self,value):return self.__class__(-super().__sub__(value))
    def __rfloordiv__(self,value):return self.__class__(self.inv()*value)
    def __iadd__(self,value):self=self+value;return self
    def __isub__(self,value):self=self-value;return self
    def __imul__(self,value):self=self*value;return self
    def __ifloordiv__(self,value):self=self //value;return self
    def __ipow__(self,value):self=self**value;return self
    def __neg__(self):return self.__class__(super().__neg__())

N=int(input())
T=list(map(int, input().split()))+[0]
A=list(map(int, input().split()))+[0]
ans=Fp(1)
for i in range(N):
    if T[i-1]<T[i] and A[i]>A[i+1]:
        ans*=T[i]==A[i]
    elif T[i-1]<T[i]:
        ans*=T[i]<=A[i]
    elif A[i]>A[i+1]:
        ans*=A[i]<=T[i]
    else:
        ans*=min(T[i],A[i])
print(ans)

Submission status: Accepted

Solution code:
import numpy as np
from itertools import groupby

N = int(input())
T = np.array(['0'] + input().split() + ['10000000000'], np.int64)
A = np.array(['10000000000'] + input().split() + ['0'], np.int64)
mod = 10 ** 9 + 7

t = (T[1:] != T[:-1]) * T[1:]
a = (A[1:] != A[:-1]) * A[:-1]
t = t[:-1]
a = a[1:]

flag = True
idx = np.where((t != 0) & (a != 0))[0]
if np.any(t[idx] != a[idx]):
    flag = False

seq = np.maximum(t, a)
if np.any(seq > T[1:-1]) or np.any(seq > A[1:-1]):
    flag = False

if flag:
    group = [(i, len(list(j))) for i, j in groupby(seq.tolist())]
    answer = 1
    for i, (key, n) in enumerate(group):
        if key == 0:
            answer *= pow(min(group[i - 1][0], group[i + 1][0]), n, mod)
            answer %= mod
    print(answer)
else:
    print(0)

Submission status: Accepted

Solution code:
import numpy as np
from itertools import groupby

N = int(input())
T = np.array(['0'] + input().split() + ['10000000000'], np.int64)
A = np.array(['10000000000'] + input().split() + ['0'], np.int64)
mod = 10 ** 9 + 7

t = (T[1:] != T[:-1]) * T[1:]
a = (A[1:] != A[:-1]) * A[:-1]
t = t[:-1]
a = a[1:]
seq = np.zeros(N, np.int64)

flag = True
tmp = np.where((t != 0) & (a != 0))[0]
if np.any(t[tmp] != a[tmp]):
    flag = False
seq = np.maximum(t, a)
if np.any(seq > T[1:-1]) or np.any(seq > A[1:-1]):
    flag = False

if flag:
    group = [(i, len(list(j))) for i, j in groupby(seq.tolist())]
    answer = 1
    for i in range(len(group)):
        if group[i][0] == 0:
            answer *= pow(min(group[i - 1][0], group[i + 1][0]), group[i][1], mod)
            answer %= mod
    print(answer)
else:
    print(0)

Submission status: Accepted

Solution code:
n = int(input())
t = list(map(int, input().split()))
a = list(map(int, input().split()))
mt_t=[0]*n
mt_a=[0]*n
last=0
for i in range(len(t)):
    if last < t[i]:
        mt_t[i] = -t[i]
        last=t[i]
    else:
        mt_t[i] = last
last=0
for i in reversed(range(len(t))):
    if last < a[i]:
        mt_a[i] = -a[i]
        last=a[i]
    else:
        mt_a[i] = last
mts = [0]*n
for i in range(len(t)):
    if mt_t[i] < 0 and mt_a[i] < 0:
        if mt_t[i] != mt_a[i]:
            print(0)
            exit()
    elif mt_t[i] < 0 or mt_a[i] < 0:
        kaku =abs(min(mt_t[i],mt_a[i]))
        kouho=max(mt_t[i],mt_a[i])
        if kouho < kaku:
            print(0)
            exit()
    mts[i] = min(mt_t[i],mt_a[i])

ans=1
for num in mts:
    if num > 0:
        ans*=num
        ans%=(10**9+7)
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
T = [int(t) for t in input().split()]
A = [int(a) for a in input().split()]

mod = 10**9+7
TM = [0]*N
TM[0] = T[0]
AM = [0]*N
AM[-1] = A[-1]
for i in range(N-1):
    if T[i] < T[i+1]:
        TM[i+1] = T[i+1]
    if A[i+1] < A[i]:
        AM[i] = A[i]

M = [0]*N
ans = 1
for i in range(N):
    if TM[i] > 0 and AM[i] > 0 and TM[i] != AM[i]:
        ans = 0
    elif TM[i] > 0 and AM[i] == 0 and TM[i] <= A[i]:
        M[i] = TM[i]
    elif TM[i] == 0 and AM[i] > 0 and AM[i] <= T[i]:
        M[i] = AM[i]
    elif TM[i] == AM[i]:
        M[i] = TM[i]
    elif TM[i] == 0 and AM[i] == 0:
        continue
    else:
        ans = 0
        break

for i in range(N):
    if M[i] > 0:
        continue
    ans *= min(T[i], A[i])
    ans %= mod

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
t = list(map(int, input().split()))
a = list(map(int, input().split()))
mod = 10**9+7
ans = 1
if n == 1 and t != a:
    print(0)
    exit()
for i in range(1,n-1):
    if t[i-1] == t[i] and a[i] == a[i+1]:
        ans = (ans*min(t[i],a[i]))%mod
    elif t[i-1] < t[i] and t[i] > a[i]:
        print(0)
        exit()
    elif a[i] > a[i+1] and t[i] < a[i]:
        print(0)
        exit()
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
T = list(map(int, input().split()))

mod = int(1e9+7)

dp = [0] * (N)
dp[0] = 1
# dp[i] : i番目までの通り数

Amax = max(A)
Aleft, Tright = -1, -1
Tmax = max(T)
for i in range(N):
  if Amax == A[i]:
    Aleft = i
    break
for i in range(N-1,-1,-1):
  if Tmax == T[i]:
    Tright = i
    break
if Aleft > Tright:
  print(0)
  exit(0)
if A[-1] != T[0]:
  print(0)
  exit(0)
  
for i in range(1,N-1):
  if A[i-1] < A[i] or T[i] > T[i+1]:
    dp[i] = dp[i-1]
  else:
    dp[i] = dp[i-1] * min(A[i], T[i]) % mod
  
print(dp[N-2])

Submission status: Accepted

Solution code:
#two alpinist
N = int(input())
A = tuple(map(int, input().split()))
B = tuple(map(int, input().split()))
mod = 10**9+7
 
#fixed[i]: i 山の高さが確定してる
fix_a= [0]*(N)
fix_b= [0]*(N)
fix_a[0] = A[0]
fix_b[-1] = B[-1]
for i in range(N-1):
    if A[i+1]>A[i]:
        fix_a[i+1] = A[i+1]
    if B[-(i+2)]>B[-(i+1)]:
        fix_b[-(i+2)] = B[-(i+2)]

ans = 1
for i in range(N):
    if fix_a[i]:
        if B[i]<fix_a[i]:
            ans = 0
            break
    if fix_b[i]:
        if A[i]<fix_b[i]:
            ans = 0
            break
            
for i in range(N):
    if fix_a[i] or fix_b[i]:
        continue
    ans *= min(A[i], B[i])
    ans %= mod
    
if A[-1] != B[0]:
    ans = 0
    
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
c = []
for i in range(n):
  c.append(min(a[i],b[i]))
d = [0 for _ in range(n)]
e = [0 for _ in range(n)]
d[0] = 1
e[-1] = 1
for i in range(1,n):
  if a[i-1] != a[i]:
    d[i] = 1
for i in range(n-1)[::-1]:
  if b[i+1] != b[i]:
    e[i] = 1
for i in range(n):
  if d[i] * e[i] == 1 and a[i] != b[i]:
    print(0)
    break
else:
  for i in range(n):
    if d[i] == 1 and a[i] != c[i]:
      print(0)
      break
    if e[i] == 1 and b[i] != c[i]:
      print(0)
      break
  else:
    ans = 1
    mod = 10 ** 9 + 7
    for i in range(n):
      if d[i] == e[i] == 0:
        ans *= c[i]
        ans %= mod
    print(ans)

Submission status: Accepted

Solution code:
from sys import stdout
printn = lambda x: stdout.write(str(x))
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
ins = lambda : input().strip()
DBG = True # and False
BIG = 999999999
R = 10**9 + 7

def ddprint(x):
  if DBG:
    print(x)

n = inn()
t = inl()
a = inl()
mx = max(t)
if max(a) != mx:
    print(0)
    exit()
for p in range(n):
    if t[p]==mx:
        break
for q in range(n-1,-1,-1):
    if a[q]==mx:
        break
if q<p:
    print(0)
    exit()
prod = 1
prev = -1
for i in range(p):
    if t[i]==prev:
        prod = (prod*prev)%R
    else:
        prev = t[i]
prev = -1
for i in range(n-1,q,-1):
    if a[i]==prev:
        prod = (prod*prev)%R
    else:
        prev = a[i]
print((prod*(mx**max(0,q-p-1)))%R)

Submission status: Accepted

Solution code:
# C - 二人のアルピニスト / Two Alpinists
import sys
import numpy as np
sys.setrecursionlimit(10 ** 7)

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N = ir()
T = np.array(lr()).astype('int64')
A = np.array(lr()).astype('int64')
MOD = 10 ** 9 + 7

T_low = T.copy()
T_low[1:][T[1:] <= T[:-1]] = 1
A_low = A.copy()
A_low[:-1][A[:-1] <= A[1:]] = 1

lower = np.maximum(T_low, A_low)
upper = np.minimum(T, A)
domain = np.maximum(0, upper - lower + 1) #変域が0の時は記録が間違い
L = len(domain); LSQ = int(L**.5 + 1) # least squares method 最小二乗推定?
domain = np.resize(domain, LSQ**2) #行列の形に無理やりする下準備（1次元）
domain[L:] = 1 #後半は全部1
domain = domain.reshape((LSQ, LSQ))
for n in range(1, LSQ):
    domain[:, n] *= domain[:, n-1]; domain[:, n] %= MOD
for n in range(1, LSQ):
    domain[n, -1] *= domain[n-1, -1]; domain[n] %= MOD
answer = domain[-1, -1]
print(answer)

Submission status: Accepted

Solution code:
MOD = 10**9+7
n = int(input())
T = list(map(int, input().split()))
A = list(map(int, input().split()))
C = [0]*n
if T[0] > A[0] or T[-1] < A[-1]:
  print(0)
  exit()
C[0], C[-1] = 1, 1
for i in range(1, n-1):
  if T[i-1] == T[i]:
    t = -T[i]
  else:
    t = T[i]
  if A[i] == A[i+1]:
    a = -A[i]
  else:
    a = A[i]
  if t > 0 and a > 0:
    if t != a:
      print(0)
      exit()
    C[i] = 1
  else:
    if t > 0:
      if t > abs(a):
        print(0)
        exit()
      C[i] = 1
    elif a > 0:
      if a > abs(t):
        print(0)
        exit()
      C[i] = 1
    else:
      C[i] = min(-t, -a)
ans = 1
for i in C:
  ans *= i
  ans %= MOD
print(ans)

Submission status: Accepted

Solution code:
import sys, bisect, math, itertools, string, queue, copy
# import numpy as np
# import scipy
from collections import Counter,defaultdict,deque
from itertools import permutations, combinations
from heapq import heappop, heappush
input = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7
def inp(): return int(input()) # n=1
def inpm(): return map(int,input().split()) # x=1,y=2
def inpl(): return list(map(int, input().split())) # a=[1,2,3,4,5,...,n]
def inpls(): return list(input().split())  # a=['1','2','3',...,'n']
def inplm(n): return list(int(input()) for _ in range(n)) # x=[] 複数行
def inplL(n): return [list(input()) for _ in range(n)]
def inplT(n): return [tuple(input()) for _ in range(n)]
def inpll(n): return [list(map(int, input().split())) for _ in range(n)] # [[2,2,2,2],[1,1,1,1],[3,3,3,3]] 
def inplls(n): return sorted([list(map(int, input().split())) for _ in range(n)]) # [[1,1,1,1],[2,2,2,2],[3,3,3,3]] 

 
def main():
    n = inp()
    t = inpl()
    a = inpl()
    m = [0 for _ in range(n)]
    m[0] = t[0]
    for i in range(1,n):
        if t[i]>t[i-1]:
            m[i] = t[i]
    m[n-1] = a[n-1]
    for i in range(n-2,-1,-1):
        if a[i]>a[i+1]:
            m[i] = a[i]
    ans = 1
    mt,ma = 0,0
    for i in range(n):
        mt = max(mt,m[i])
        ma = max(ma,m[n-1-i])
        if mt != t[i] or ma != a[n-1-i]:
            print(0)
            return
    for i in range(n):
        if m[i] == 0:
            ans = (ans*min(t[i],a[i]))%mod
    print(ans)
    
if __name__ == "__main__":
    main()