Problem:


Score : 100 points

Problem Statement

Let N be a positive integer.
You are given a string s of length N - 1, consisting of < and >.

Find the number of permutations (p_1, p_2, \ldots, p_N) of (1, 2, \ldots, N) that satisfy the following condition, modulo 10^9 + 7:

For each i (1 \leq i \leq N - 1), p_i < p_{i + 1} if the i-th character in s is <, and p_i > p_{i + 1} if the i-th character in s is >.

Constraints

N is an integer.

2 \leq N \leq 3000

s is a string of length N - 1.

s consists of < and >.

Input

Input is given from Standard Input in the following format:

N
s

Output

Print the number of permutations that satisfy the condition, modulo 10^9 + 7.

Sample Input 1

4
<><

Sample Output 1

5

There are five permutations that satisfy the condition, as follows:

(1, 3, 2, 4)

(1, 4, 2, 3)

(2, 3, 1, 4)

(2, 4, 1, 3)

(3, 4, 1, 2)

Sample Input 2

5
<<<<

Sample Output 2

1

There is one permutation that satisfies the condition, as follows:

(1, 2, 3, 4, 5)

Sample Input 3

20
>>>><>>><>><>>><<>>

Sample Output 3

217136290

Be sure to print the number modulo 10^9 + 7.



Sample input:
4
<><


Sample output:
5

Submission status: Accepted

Solution code:
import sys,bisect,string,math,time,functools,random,fractions
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
rep=range;R=range
def Golf():n,*t=map(int,open(0).read().split())
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def MI():return map(int,input().split())
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def NLI(n):return [[int(i) for i in input().split()] for i in range(n)]
def NLI_(n):return [[int(i)-1 for i in input().split()] for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def RA():return map(int,open(0).read().split())
def RLI(n=8,a=1,b=10):return [random.randint(a,b)for i in range(n)]
def RI(a=1,b=10):return random.randint(a,b)
def Rtest(T):
    case,err=0,0
    for i in range(T):
        inp=INP()
        a1,ls=naive(*inp)
        a2=solve(*inp)
        if a1!=a2:
            print((a1,a2),inp)
            err+=1
        case+=1
    print('Tested',case,'case with',err,'errors')
def GI(V,E,ls=None,Directed=False,index=1):
    org_inp=[];g=[[] for i in range(V)]
    FromStdin=True if ls==None else False
    for i in range(E):
        if FromStdin:
            inp=LI()
            org_inp.append(inp)
        else:
            inp=ls[i]
        if len(inp)==2:
            a,b=inp;c=1
        else:
            a,b,c=inp
        if index==1:a-=1;b-=1
        aa=(a,c);bb=(b,c);g[a].append(bb)
        if not Directed:g[b].append(aa)
    return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1):
    #h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1) # sample usage
    mp=[boundary]*(w+2);found={}
    for i in R(h):
        s=input()
        for char in search:
            if char in s:
                found[char]=((i+1)*(w+2)+s.index(char)+1)
                mp_def[char]=mp_def[replacement_of_found]
        mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
    mp+=[boundary]*(w+2)
    return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def accum(ls):
    rt=[0]
    for i in ls:rt+=[rt[-1]+i]
    return rt
def bit_combination(n,base=2):
    rt=[]
    for tb in R(base**n):s=[tb//(base**bt)%base for bt in R(n)];rt+=[s]
    return rt
def gcd(x,y):
    if y==0:return x
    if x%y==0:return y
    while x%y!=0:x,y=y,x%y
    return y
def YN(x):print(['NO','YES'][x])
def Yn(x):print(['No','Yes'][x])
def show(*inp,end='\n'):
    if show_flg:print(*inp,end=end)

mo=10**9+7
#mo=998244353
inf=float('inf')
FourNb=[(-1,0),(1,0),(0,1),(0,-1)];EightNb=[(-1,0),(1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('WENS',FourNb));cursol=dict(zip('LRUD',FourNb))
l_alp=string.ascii_lowercase
#sys.setrecursionlimit(10**9)
read=sys.stdin.buffer.read;readline=sys.stdin.buffer.readline;input=lambda:sys.stdin.readline().rstrip()


## return prime factors of N as dictionary {prime p:power of p}
## within 2 sec for N = 2*10**20+7
def primeFactor(N):
    i,n=2,N
    ret={}
    d,sq=2,99
    while i<=sq:
        k=0
        while n%i==0:
            n,k,ret[i]=n//i,k+1,k+1
        if k>0 or i==97:
            sq=int(n**(1/2)+0.5)
        if i<4:
            i=i*2-1
        else:
            i,d=i+d,d^6
    if n>1:
        ret[n]=1
    return ret

## return divisors of n as list
def divisor(n):
    div=[1]
    for i,j in primeFactor(n).items():
        div=[(i**k)*d for d in div for k in range(j+1)]
    return div

## return the list of prime numbers in [2,N], using eratosthenes sieve
## around 800 ms for N = 10**6  by PyPy3 (7.3.0) @ AtCoder
def PrimeNumSet(N):
    M=int(N**0.5)
    seachList=[i for i in range(2,N+1)]
    primes=[]
    while seachList:
        if seachList[0]>M:
            break
        primes.append(seachList[0])
        tmp=seachList[0]
        seachList=[i for i in seachList if i%tmp!=0]
    return primes+seachList


## retrun LCM of numbers in list b
## within 2sec for no of B = 10*5  and  Bi < 10**6
def LCM(b,mo=10**9+7):
    prs=PrimeNumSet(max(b))
    M=dict(zip(prs,[0]*len(prs)))
    for i in b:
        dc=primeFactor(i)
        for j,k in dc.items():
            M[j]=max(M[j],k)
    
    r=1
    for j,k in M.items():
        if k!=0:
            r*=pow(j,k,mo)
            r%=mo
    return r

show_flg=False
show_flg=True

ans=0

n=I()
s=input()
dp=[0]*n
for i in range(n):
    dp[i]=1
    
for k in range(n-1,0,-1):
    nx=[0]*n
    if s[n-1-k]=='>':
        for i in range(k+1):
            nx[0]+=dp[i]
            nx[i]+=-dp[i]
        
    elif s[n-1-k]=='<':
        for i in range(k+1):
            nx[i]+=dp[i]
            nx[k]+=-dp[i]
        
    for i in range(k):
        nx[i+1]=(nx[i+1]+nx[i])%mo


    #show(dp)
    dp=nx[:]
    
    
print(dp[0]%mo)

Submission status: Accepted

Solution code:
# T - Permutation
n = int(input())
s = input()
MOD = 10**9+7

# dp[i][j]:i番目まで決めたとき、i番目の数よりも大きい数がj個残っている場合の数。
dp = [[0 for _ in range(n)] for _ in range(n+1)]

# 今i-1番目の数より大きい数が3個残っているとする。
# s[i]=='<'のとき、i番目の数として、その3個すべてが使える。
# そうすると、i番目の数より大きい数が2個、1個、0個残っている場合に遷移する。
# つまり、i番目の数より大きい数がj個残っている場合には、
# i-1番目の数より大きい数がj+1,j+2...n-i+1個残っている場合から遷移する。
# s[i]=='>'のとき、i番目の数として、その3個を除いた数字が使える。
# そうすると、i+1番目の数より大きい数が3個、4個...n-i-1個残っている場合に遷移する。
# つまり、i番目の数より大きい数がj個残っている場合には、
# i-1番目の数より大きい数がj,j-1...0個残っている場合から遷移する。

# ただし、下記のプログラムでは計算量がO(n**3)になってしまう。
# kのループで累積和を使用することで、O(n**2)にできる。
#
# for i in range(n):
#   dp[1][i] = 1
# for i in range(2,n+1):
#   if s[i-2] == '<':
#     for j in range(n-i+1):
#       for k in range(j+1,n-i+2):
#         dp[i][j] += dp[i-1][k]
#         dp[i][j] %= MOD
#   else:
#     for j in range(n-i+1):
#       for k in range(j+1):
#         dp[i][j] += dp[i-1][k]
#         dp[i][j] %= MOD

for i in range(n):
  dp[1][i] = 1
for i in range(2,n+1):
  csum = [0 for _ in range(n-i+2)]
  csum[0] = dp[i-1][0]
  for k in range(1,n-i+2):
    csum[k] += csum[k-1]+dp[i-1][k]
  if s[i-2] == '<':
    for j in range(n-i+1):
      dp[i][j] += csum[n-i+1]-csum[j]
      dp[i][j] %= MOD
  else:
    for j in range(n-i+1):
      dp[i][j] += csum[j]
      dp[i][j] %= MOD
print(dp[n][0])

Submission status: Accepted

Solution code:
N = int(input())
s = list(input())
MOD = 10 ** 9 + 7

DP = [[0] * N for _ in range(N)]

for i in range(N):
  DP[0][i] = 1

for i in range(1, N):
  if s[i - 1] == "<":
    for j in range(N - i - 1, -1, -1):
      DP[i][j] = (DP[i][j + 1] + DP[i - 1][j + 1]) % MOD
  else:
    for j in range(N - i):
      DP[i][j] = (DP[i][j - 1] + DP[i - 1][j]) % MOD

print(DP[-1][0])

Submission status: Accepted

Solution code:
N=int(input())
s=input()
dp=[[0 for _ in range(N+1)] for i in range(N+1)]
MOD=10**9+7
dp[0][N]=1
dp[1]=[1]*N+[0]

cum=[0 for _ in range(N+2)]
for i in range(1,N):
    cum[0]=0
    for z in range(1,N-i+2):
        cum[z]=(cum[z-1]+dp[i][z-1])%MOD

    if s[i-1]=='<':
        for j in range(0,N-i):
            dp[i+1][j] =(dp[i+1][j] +cum[N-i+1]-cum[j+1])%MOD
    else:
        for j in range(0,N-i):
            dp[i+1][j]=(dp[i+1][j] + cum[j+1])%MOD

print(dp[N][0])

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
#from math import gcd
import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache

#############
# Constants #
#############

MOD = 10**9+7
INF = float('inf')
AZ = "abcdefghijklmnopqrstuvwxyz"

#############
# Functions #
#############

######INPUT######
def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]


#####Shorten#####
def DD(arg): return defaultdict(arg)

#####Inverse#####
def inv(n): return pow(n, MOD-2, MOD)

######Combination######
kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n): return kaijo_memo[n]
  if(len(kaijo_memo) == 0): kaijo_memo.append(1)
  while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n): return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0): gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n): gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if n == r: return 1
  if n < r or r < 0: return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret

######Factorization######
def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1: arr.append([temp, 1])
  if arr==[]: arr.append([n, 1])
  return arr

#####MakeDivisors######
def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors

#####MakePrimes######
def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum

#####GCD#####
def gcd(a, b):
    while b: a, b = b, a % b
    return a

#####LCM#####
def lcm(a, b):
    return a * b // gcd (a, b)

#####BitCount#####
def count_bit(n):
  count = 0
  while n:
    n &= n-1
    count += 1
  return count

#####ChangeBase#####
def base_10_to_n(X, n):
  if X//n: return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

def base_10_to_n_without_0(X, n):
  X -= 1
  if X//n: return base_10_to_n_without_0(X//n, n)+[X%n]
  return [X%n]

#####IntLog#####
def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count

#############
# Main Code #
#############

N = I()
S = S()

def ACC1(l):
  N = len(l)
  ret = [0]*(N+1)
  for i in range(N):
    ret[i+1] = ret[i]+l[i]
    ret[i+1] %= MOD
  return ret

prev = [1 for j in range(N)]

for i in range(N-1):
  now = [0 for j in range(N)]
  s = S[i]
  for j in range(N):
    if s == "<":
      if j < N-1-i:
        now[j] += prev[j]
        now[N-1-i] -= prev[j]
    else:
      if j:
        now[0] += prev[j]
        now[j] -= prev[j]
  prev = ACC1(now)[1:]
print(prev[0])

Submission status: Accepted

Solution code:
from sys import stdin
import sys
import math
from functools import reduce
import functools
import itertools
from collections import deque,Counter,defaultdict
from operator import mul
import copy
# ! /usr/bin/env python
# -*- coding: utf-8 -*-
import heapq
sys.setrecursionlimit(10**6)
INF =  float("inf")
import bisect
import statistics
mod = 10**9+7

N = int(input())
s = input()

dp = [[0 for j in range(N+1)] for i in range(N+1)]
for j in range(1,N+1):
    dp[1][j] = 1

for i in range(2,N+1):
    a = [0 for i in range(N-i+3)]
    for k in range(1,N-i+3):
        a[k] = (a[k-1] + dp[i-1][k]) % mod

    for j in range(1,N-i+2):
        if s[i-2] == "<":
            dp[i][j] = (a[N-i+2] - a[j]) % mod
            # for k in range(1,N-i-j+3):
            #     dp[i][j] = (dp[i][j] + dp[i-1][j+k]) % mod
        else:
            dp[i][j] = (a[j] - a[0]) % mod
            # for k in range(1,j+1):
            #     dp[i][j] = (dp[i][j] + dp[i-1][k]) % mod

print(dp[N][1] % mod)

Submission status: Accepted

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
from bisect import bisect_right, bisect_left
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor, gamma, log
from operator import mul
from functools import reduce
from copy import deepcopy

sys.setrecursionlimit(2147483647)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): pass
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 10 ** 9 + 7

n = I()

fac = [1] * (n + 1)
inv = [1] * (n + 1)
for j in range(1, n + 1):
    fac[j] = fac[j-1] * j % mod


inv[n] = pow(fac[n], mod-2, mod)
for j in range(n-1, -1, -1):
    inv[j] = inv[j+1] * (j+1) % mod


def comb(n, r):
    if r > n or n < 0 or r < 0:
        return 0
    return fac[n] * inv[n - r] * inv[r] % mod

s = input()
dp = [[0] * n for _ in range(n)]
dp[0][0] = 1
for i in range(1, n):
    ret = 0
    if s[i - 1] == "<":
        for j in range(i - 1, -1, -1):
            ret += dp[i - 1][j]
            ret %= mod
            dp[i][j] = ret
    else:
        for j in range(i):
            ret += dp[i - 1][j]
            dp[i][j + 1] = ret
        dp[i][i] = ret

print(sum(dp[-1]) % mod)

Submission status: Accepted

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
from bisect import bisect_right, bisect_left
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor, gamma, log
from operator import mul
from functools import reduce
from copy import deepcopy

sys.setrecursionlimit(2147483647)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): pass
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 10 ** 9 + 7

n = I()

fac = [1] * (n + 1)
inv = [1] * (n + 1)
for j in range(1, n + 1):
    fac[j] = fac[j-1] * j % mod


inv[n] = pow(fac[n], mod-2, mod)
for j in range(n-1, -1, -1):
    inv[j] = inv[j+1] * (j+1) % mod


def comb(n, r):
    if r > n or n < 0 or r < 0:
        return 0
    return fac[n] * inv[n - r] * inv[r] % mod

s = input()
dp = [[0] * n for _ in range(n)]
dp[0][0] = 1
for i in range(1, n):
    ret = 0
    if s[i - 1] == "<":
        for j in range(i - 1, -1, -1):
            ret += dp[i - 1][j]
            ret %= mod
            dp[i][j] = ret
    else:
        for j in range(1, i + 1):
            ret += dp[i - 1][j - 1]
            dp[i][j] = ret
        dp[i][i] = ret

print(sum(dp[-1]) % mod)

Submission status: Accepted

Solution code:
def solve():
  N = int(input())
  s = input()
  mod = 10**9+7
  dp = [[0]*N for _ in range(N)]
  dp[-1][0]=1
  for i in range(N-2,-1,-1):
    if s[i]=='>':
      for j in range(N-i-2,-1,-1):
        dp[i][j] = dp[i][j+1]+dp[i+1][j]
        dp[i][j] %= mod
    else:
      for j in range(1,N-i):
        dp[i][j] = dp[i][j-1]+dp[i+1][j-1]
        dp[i][j] %= mod
  ans = sum(dp[0])%mod
  return ans
print(solve())

Submission status: Accepted

Solution code:
import sys

stdin = sys.stdin


def ni(): return int(ns())


def na(): return list(map(int, stdin.readline().split()))


def naa(N): return [na() for _ in range(N)]


def ns(): return stdin.readline().rstrip()  # ignore trailing spaces


N = ni()
s = ns()

mod = 10 ** 9 + 7
dp = [1] * N

for i, ss in enumerate(s):
    sdp = []
    ans = 0
    for d in dp:
        ans = (ans + d) % mod
        sdp.append(ans)
    dp = []
    if ss == "<":
        for j in range(N-1-i):
            dp.append(sdp[j])
    else:
        for j in range(N-1-i):
            dp.append((sdp[N-1-i] - sdp[j]) % mod)
    # print(dp)
print(dp[0])

Submission status: Accepted

Solution code:
n = int(input())
s = input()
mod = 10**9 + 7

D = [[0] * (n+1) for i in range(n)]
D[0][0] = 1
for i in range(1, n):
    if s[i-1] == "<":
        for j in range(i):
            D[i][0] = (D[i][0] + D[i-1][j]) % mod
            D[i][j+1] = (D[i][j+1] - D[i-1][j]) % mod
    else:
        for j in range(i):
            D[i][j+1] = (D[i][j+1] + D[i-1][j]) % mod
            D[i][i+1] = (D[i][i+1] - D[i-1][j]) % mod
    for j in range(1, n+1):
        D[i][j] = (D[i][j] + D[i][j-1]) % mod
# print(D)
print(sum(D[-1]) % mod)

Submission status: Accepted

Solution code:

def resolve():
    MOD = 10 ** 9 + 7
    N = int(input())
    S = input()

    # i番目の数字より大きい数字が残りj個の通り数
    dp = [[0] * (N + 1) for _ in range(N + 1)]
    for j in range(N):
        dp[0][j] = 1

    for i in range(N):
        cum = [0] * (N + 1)
        for j in range(N):
            cum[j+1] = (cum[j] + dp[i][j]) % MOD

        for j in range(N - i - 1):
            if S[i] == "<":
                dp[i+1][j] = (cum[N]-cum[j+1]) % MOD
            else:
                dp[i+1][j] = (cum[j+1] - cum[0]) % MOD

    print(dp[N - 1][0])


if __name__ == "__main__":
    resolve()

Submission status: Accepted

Solution code:

def resolve():
    MOD = 10**9+7
    N = int(input())
    S = input()

    dp = [[0]*(N) for _ in range(N)]
    for j in range(N):
        dp[0][j] = 1


    for i in range(N-1):
        # 累積和
        cum_A = [0]*(N+1)
        for j in range(N-i):
            cum_A[j+1] = (cum_A[j] + dp[i][j]) % MOD

        if S[i] == "<":
            for j in range(N-i):
                # 引き算がある為、負の mod に気を付ける
                dp[i+1][j] = (cum_A[N - i] - cum_A[j + 1] + MOD) % MOD
        else:
            for j in range(N-i):
                dp[i+1][j] = cum_A[j + 1]
    print(dp[N-1][0])


if __name__ == "__main__":
    resolve()

Submission status: Accepted

Solution code:
MOD = 10 ** 9 + 7
n = int(input())
s = input()
dp = [1] * n
for i, c in enumerate(s):
    sz = n - i
    ndp = [0] * (sz - 1)
    if c == '<':
        now = 0
        for k in range(sz - 1):
            now = (now + dp[k]) % MOD
            ndp[k] = now
    else:
        now = 0
        for k in range(sz - 2, -1, -1):
            now = (now + dp[k+1]) % MOD
            ndp[k] = now
    dp = ndp
print(dp[0])

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

#from collections import defaultdict
#from heapq import heappush, heappop
#import numpy as np
from itertools import accumulate
import sys

sys.setrecursionlimit(10**6)
input = sys.stdin.buffer.readline
INF = 10 ** 9 + 1  # sys.maxsize # float("inf")
MOD = 10 ** 9 + 7

debug_indent = 0


def debug(*x):
    global debug_indent
    x = list(x)
    indent = 0
    if x[0].startswith("enter") or x[0][0] == ">":
        indent = 1
    if x[0].startswith("leave") or x[0][0] == "<":
        debug_indent -= 1
    x[0] = "  " * debug_indent + x[0]
    print(*x, file=sys.stderr)
    debug_indent += indent


def solve(N, lessthan):
    k = 1
    table = [0] * (k + 1)
    if lessthan[-1]:
        for i in range(k + 1):
            table[i] = k - i
    else:
        for i in range(k + 1):
            table[i] = i

    for k in range(2, N):
        newtable = [0] * (k + 1)
        acc = [0] + list(accumulate(table))
        if lessthan[-k]:
            for i in range(k + 1):
                # for j in range(k - i):
                #    newtable[i] += table[j + i]
                newtable[i] += acc[k] - acc[i]
        else:
            for i in range(k + 1):
                # for j in range(i):
                #    newtable[i] += table[j]
                newtable[i] += acc[i]
        table = [x % MOD for x in newtable]
    return sum(table) % MOD


def main():
    # parse input
    N = int(input())
    lessthan = [c == ord("<") for c in input().strip()]
    print(solve(N, lessthan))


# tests
T0 = """
2
>
"""


def test_T0():
    """
    >>> as_input(T0)
    >>> main()
    1
    """


T01 = """
3
<<
"""


def test_T01():
    """
    >>> as_input(T01)
    >>> main()
    1
    """


T02 = """
3
>>
"""


def test_T02():
    """
    >>> as_input(T02)
    >>> main()
    1
    """


T03 = """
3
<>
"""


def test_T03():
    """
    >>> as_input(T03)
    >>> main()
    2
    """


T1 = """
4
<><
"""


def test_T1():
    """
    >>> as_input(T1)
    >>> main()
    5
    """


T2 = """
5
<<<<
"""


def test_T2():
    """
    >>> as_input(T2)
    >>> main()
    1
    """


T3 = """
20
>>>><>>><>><>>><<>>
"""


def test_T3():
    """
    >>> as_input(T3)
    >>> main()
    217136290
    """
# add tests above


def _test():
    import doctest
    doctest.testmod()


def as_input(s):
    "use in test, use given string as input file"
    import io
    global read, input
    f = io.StringIO(s.strip())

    def input():
        return bytes(f.readline(), "ascii")

    def read():
        return bytes(f.read(), "ascii")


USE_NUMBA = False
if (USE_NUMBA and sys.argv[-1] == 'ONLINE_JUDGE') or sys.argv[-1] == '-c':
    print("compiling")
    from numba.pycc import CC
    cc = CC('my_module')
    cc.export('solve', solve.__doc__.strip().split()[0])(solve)
    cc.compile()
    exit()
else:
    input = sys.stdin.buffer.readline
    read = sys.stdin.buffer.read

    if (USE_NUMBA and sys.argv[-1] != '-p') or sys.argv[-1] == "--numba":
        # -p: pure python mode
        # if not -p, import compiled module
        from my_module import solve  # pylint: disable=all
    elif sys.argv[-1] == "-t":
        print("testing")
        _test()
        sys.exit()
    elif sys.argv[-1] != '-p' and len(sys.argv) == 2:
        # input given as file
        input_as_file = open(sys.argv[1])
        input = input_as_file.buffer.readline
        read = input_as_file.buffer.read

    main()

Submission status: Accepted

Solution code:
N = int(input())
s = input()
MOD = 10**9+7

#A1 ... AnのBIT(1-indexed)
BIT = [0]*(N+1)

#A1 ~ Aiまでの和 O(logN)
def BIT_query(idx):
    res_sum = 0
    while idx > 0:
        res_sum += BIT[idx]
        idx -= idx&(-idx)
    return res_sum

#Ai += x O(logN)
def BIT_update(idx,x):
    while idx <= N:
        BIT[idx] += x
        idx += idx&(-idx) #BIT_update(0, )をすると while が終わらない
    return


dp = [[0]*N for _ in range(N)] # dp[i][k]：i番目まで見た時に，i番目の要素より小さい値の個数がkの時のパターン数 
for k in range(N): dp[0][k] = 1

for i in range(1, N):
    BIT = [0]*(N+1)
    for k in range(N): BIT_update(k+1, dp[i-1][k]) #BIT_update(0, )をすると while が終わらない
    if s[i-1] == '<':
        for k in range(N-i): dp[i][k] = BIT_query(k+1) % MOD #sum([dp[i-1][j] for j in range(k+1)])
    else:
        for k in range(N): dp[i][k] = (BIT_query(N) - BIT_query(k+1)) % MOD #sum([dp[i-1][j] for j in range(k+1, N)])

print(dp[-1][0])

Submission status: Accepted

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


n = int(input())
s = input()
dp = [[0]*(n+1) for _ in range(n+1)]
dp[1][1] = 1
M = 10**9+7
for i in range(2, n+1):
    v = 0
    if s[i-2]=="<":
        for j in range(1,i+1):
            # j: 最後の数
            dp[i][j] = v
            v += dp[i-1][j]
            v %= M
        dp[i][i] = v
    else:
        for j in range(i,1,-1):
            # j: 最後の数
            dp[i][j] = v
            v += dp[i-1][j-1]
            v %= M
        dp[i][1] = v
#     print(dp)
ans = 0
for item in dp[n]:
    ans += item
    ans %= M
print(ans)

Submission status: Accepted

Solution code:
from itertools import accumulate
mod = 10 ** 9 + 7

N = int(input())
S = input()

# i箇所まで決めた、最後の数より大きいのがjこ
dp = [1] * N

for i, s in enumerate(S, 1):
    dp = list(accumulate(dp))
    newDP = [0] * N
    if s == "<":
        for j in range(N - i):
            newDP[j] = dp[N - i] - dp[j]
            newDP[j] %= mod
    else:
        for j in range(N - i):
            newDP[j] = dp[j] % mod
    dp = newDP

print(dp[0])

Submission status: Accepted

Solution code:
from numpy import*;M,n,S=10**9+7,int(input()),input();d=ones(n,int)
for s in S:d=(cumsum(d[1:][::-1])[::-1],cumsum(d[:-1]))[s==">"]%M
print(d[0])

Submission status: Accepted

Solution code:
from numpy import*;M,n,S=10**9+7,int(input()),input();d=ones(n,int)
for s in S:d=(cumsum(d[::-1][:-1])[::-1],cumsum(d[:-1]))[s==">"]%M
print(d[0])

Submission status: Accepted

Solution code:
from numpy import*;M=10**9+7;n=int(input());S=input();d=ones(n,int)
for s in S:d=(cumsum(d[::-1][:-1])[::-1],cumsum(d[:-1]))[s==">"]%M
print(d[0])

Submission status: Accepted

Solution code:
from numpy import*;I=input;M=10**9+7;n=int(I());S=I();d=ones(n,int)
for s in S:d=(cumsum(d[::-1][:-1])[::-1],cumsum(d[:-1]))[s==">"]%M
print(d[0])

Submission status: Accepted

Solution code:
import numpy as np
from itertools import accumulate
MOD = 10**9+7
n = int(input())
S = input()
dp = np.ones(n, dtype=np.int64)
for s in S:
  if s == "<":
    dp = np.cumsum(dp[::-1][:-1])[::-1]%MOD
  else:
    dp = np.cumsum(dp[:-1])%MOD
ans = dp[0]
print(ans)

Submission status: Accepted

Solution code:
MOD = 10**9+7
n = int(input())
S = input()
def main():
  dp = [[0]*(n+1) for _ in range(n+1)]
  for j in range(n):
    dp[1][j] = 1
  for i, s in enumerate(S, 1):
    if s == "<":
      dp[i+1][n-(i+1)] = dp[i][n-i]
      for j in range(n-i-2, -1, -1):
        dp[i+1][j] = dp[i+1][j+1] + dp[i][j+1]
        dp[i+1][j] %= MOD
    else:
      dp[i+1][0] = dp[i][0]
      for j in range(1, n-i):
        dp[i+1][j] = dp[i+1][j-1] + dp[i][j]
        dp[i+1][j] %= MOD
  ans = dp[n][0]
  print(ans)
if __name__ == "__main__":
  main()

Submission status: Accepted

Solution code:
def solve():
    MOD = 10**9 + 7

    N = int(input())
    Ss = input().rstrip()

    dp = [1] * N
    for i, S in enumerate(Ss, start=1):
        dp2 = [0] * N
        if S == '<':
            for j in range(N-i):
                dp2[j] = dp2[j-1] + dp[j]
                dp2[j] %= MOD
        else:
            for j in reversed(range(N-i)):
                dp2[j] = dp2[j+1] + dp[j+1]
                dp2[j] %= MOD
        dp = dp2

    print(dp[0])


solve()

Submission status: Accepted

Solution code:


def read_int():
    return int(input().strip())


def read_ints():
    return list(map(int, input().strip().split(' ')))


def solve():
    """
    OPT[i][j] - number of solutions for s[:i] and ends in j uses only 1..i

    OPT[i+1][j] = sum(OPT[i][k]) k > j               if s[i+1] = '>'
    OPT[i+1][j] = sum(OPT[i][k]) k < j
    """
    N = read_int()
    s = input().strip()
    dp = [0]*N
    dp[0] = 1
    new_dp = [0]*N
    modulo = 10**9+7
    for i in range(1, N):
        T = 0
        if s[i-1] == '<':
            for j in range(1, i+1):
                T = (T+dp[j-1])%modulo
                dp[j-1] = 0
                new_dp[j] = T
        else: #s[i-1] == '>'
            for j in range(i, -1, -1):
                T = (T+dp[j])%modulo
                dp[j] = 0
                new_dp[j] = T
        dp, new_dp = new_dp, dp
    return sum(dp)%modulo


if __name__ == '__main__':
    print(solve())

Submission status: Accepted

Solution code:
nax = 3005
dp = [[0 for _ in range(nax)] for _ in range(nax)]
mod = 1e9+7
def add(a, b):
    c = a + b
    if c >= mod:
        c -= mod
    return c
def subtract(a, b):
    c = a - b
    if c < 0:
        c += mod
    return c

# dp[i][j] - the number of ways to put numbers in prefix of size 'i'
# such that the last number is 'j'
def main():
    n = int(raw_input())
    s = raw_input()    
    pref_sum = [0 for _ in range(n+1)]
    dp[1][1] = 1
    pref_sum[1] = 1
    for length in range(2, n+1):
        
        for b in range(1, length+1):
            if s[length-2] == '<':
                L = 1
                R = b-1
            else: # == '>'
                L = b
                R = length-1
            
            dp[length][b] = add(dp[length][b], subtract(pref_sum[R], pref_sum[L-1]))
            
            # for i in range(L, R+1):
            #     dp[length][b] = add(dp[length][b], dp[length-1][i])
                
            # for a in range(1, length):
            #     real_a = a
            #     if a >= b:
            #         real_a += 1
            #     if (real_a < b) != (s[length-2] == '<'):
            #         continue
            #     dp[length][b] = add(dp[length][b], dp[length-1][a])
        for b in range(1, length+1):
            pref_sum[b] = dp[length][b]
            pref_sum[b] = add(pref_sum[b], pref_sum[b-1])
        
    answer = 0
    for i in range(1, n+1):
        answer = add(answer, dp[n][i])
    answer = int(answer)
    print(answer)
    
main()

Submission status: Accepted

Solution code:
MOD = 10**9 + 7

N = int(input())
s = input()

# dp[i][j] := i 番目まで決めて i 番目の数より大きいものが j 個のときの場合の数
dp = [[0]*N for _ in range(N)]
dp[0] = [1]*(N+1)
for i in range(N-1):
    # 累積和をとっておく
    for j in range(N-1):
        dp[i][j+1] += dp[i][j]
    for j in range(N-i-1):
        if s[i] == '<':
            dp[i+1][j] += dp[i][N-i-1]-dp[i][j]
        else:
            dp[i+1][j] += dp[i][j]
        dp[i+1][j] %= MOD

print(dp[N-1][0])

Submission status: Accepted

Solution code:
from itertools import accumulate

mod = 10 ** 9 + 7

N = int(input())
S = input()

dp = [1] * N
for s in S:
    if s == "<":
        dp = [a % mod for a in accumulate(dp[:-1])]
    else:
        dp = [a % mod for a in accumulate(reversed(dp[1:]))]
        dp.reverse()

print(dp[0])