Problem:


Score : 500 points

Problem Statement

There are 2N squares arranged from left to right. You are given a string of length 2N representing the color of each of the squares.

The color of the i-th square from the left is black if the i-th character of S is B, and white if that character is W.

You will perform the following operation exactly N times: choose two distinct squares, then invert the colors of these squares and the squares between them. Here, to invert the color of a square is to make it white if it is black, and vice versa.  

Throughout this process, you cannot choose the same square twice or more. That is, each square has to be chosen exactly once.

Find the number of ways to make all the squares white at the end of the process, modulo 10^9+7.

Two ways to make the squares white are considered different if and only if there exists i (1 \leq i \leq N) such that the pair of the squares chosen in the i-th operation is different.

Constraints

1 \leq N \leq 10^5

|S| = 2N

Each character of S is B or W.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the number of ways to make all the squares white at the end of the process, modulo 10^9+7. If there are no such ways, print 0.

Sample Input 1

2
BWWB

Sample Output 1

4

There are four ways to make all the squares white, as follows:

Choose Squares 1, 3 in the first operation, and choose Squares 2, 4 in the second operation.

Choose Squares 2, 4 in the first operation, and choose Squares 1, 3 in the second operation.

Choose Squares 1, 4 in the first operation, and choose Squares 2, 3 in the second operation.

Choose Squares 2, 3 in the first operation, and choose Squares 1, 4 in the second operation.

Sample Input 2

4
BWBBWWWB

Sample Output 2

288

Sample Input 3

5
WWWWWWWWWW

Sample Output 3

0



Sample input:
2
BWWB


Sample output:
4

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import *
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def LS(): return list(map(list, input().split()))
def S(): return list(input().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')

#A
def A():
    m, d = LI()
    ans = 0
    for i in range(1, m + 1):
        for j in range(10, d + 1):
            if int(str(j)[0]) < 2 or int(str(j)[1]) < 2:
                continue
            if i == int(str(j)[0]) * int(str(j)[1]):
                ans += 1
    print(ans)
    return

#B
def B():
    n, l = LI()
    a = LI()
    d0 = defaultdict(int)
    d1 = defaultdict(int)
    for i in a:
        d0[i] += 1
    for i in range(n):
        b = 0
        for k in range(i+1, n):
            if a[i] > a[k]:
                b += 1
        d1[i] = b
    ans = 0
    d2 = list(d0.items())
    d2.sort()
    d3 = defaultdict(int)
    d = 0
    for key, value in d2:
        d3[key] = d
        d += value
    for i in range(n):
        ans += d3[a[i]] * l * (l-1) // 2 + d1[i] * l
        ans %= mod
    print(ans % mod)
    return

#C
def C():
    n = II()
    s = S()
    if s[0] == "W":
        print(0)
        return
    lis = [0] * (2 * n)
    l = [0] * (2 * n)
    l[0] = 1
    for i in range(1, 2 * n):
        lis[i] = (lis[i-1] ^ (s[i] == s[i-1]))
        l[i] += l[i - 1] + (lis[i] == 0)
    ans = 1
    if l[-1] != n or s[0] == "W":
        print(0)
        return
    k = 1
    for i in range(2 * n):
        if lis[i]:
            ans *= l[i] - (k - 1)
            ans %= mod
            k += 1
    print(ans * math.factorial(n) % mod)
    return

#D
def D():
    return

#E
def E():
    return

#F
def F():
    return

#G
def G():
    return

#H
def H():
    return

#Solve
if __name__ == '__main__':
    C()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import *
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def LS(): return list(map(list, input().split()))
def S(): return list(input().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')

#A
def A():
    m, d = LI()
    ans = 0
    for i in range(1, m + 1):
        for j in range(10, d + 1):
            if int(str(j)[0]) < 2 or int(str(j)[1]) < 2:
                continue
            if i == int(str(j)[0]) * int(str(j)[1]):
                ans += 1
    print(ans)
    return

#B
def B():
    n, l = LI()
    a = LI()
    d0 = defaultdict(int)
    d1 = defaultdict(int)
    for i in a:
        d0[i] += 1
    for i in range(n):
        b = 0
        for k in range(i+1, n):
            if a[i] > a[k]:
                b += 1
        d1[i] = b
    ans = 0
    d2 = list(d0.items())
    d2.sort()
    d3 = defaultdict(int)
    d = 0
    for key, value in d2:
        d3[key] = d
        d += value
    for i in range(n):
        ans += d3[a[i]] * l * (l-1) // 2 + d1[i] * l
        ans %= mod
    print(ans % mod)
    return

#C
def C():
    n = II()
    s = S()
    lis = [0] * (2 * n)
    for i in range(1, 2 * n):
        lis[i] = (lis[i-1] ^ (s[i] == s[i-1]))
    l = [0] * (2 * n)
    for i in range(2 * n):
        l[i] += l[i - 1] + (lis[i] == 0)
    ans = 1
    if l[-1] != n or s[0] == "W":
        print(0)
        return
    k = 1
    for i in range(2 * n):
        if lis[i]:
            ans *= l[i] - (k - 1)
            ans %= mod
            k += 1
    print(ans * math.factorial(n) % mod)
    return

#D
def D():
    return

#E
def E():
    return

#F
def F():
    return

#G
def G():
    return

#H
def H():
    return

#Solve
if __name__ == '__main__':
    C()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import *
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def LS(): return list(map(list, input().split()))
def S(): return list(input().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')

#A
def A():
    m, d = LI()
    ans = 0
    for i in range(1, m + 1):
        for j in range(10, d + 1):
            if int(str(j)[0]) < 2 or int(str(j)[1]) < 2:
                continue
            if i == int(str(j)[0]) * int(str(j)[1]):
                ans += 1
    print(ans)
    return

#B
def B():
    n, l = LI()
    a = LI()
    d0 = defaultdict(int)
    d1 = defaultdict(int)
    for i in a:
        d0[i] += 1
    for i in range(n):
        b = 0
        for k in range(i+1, n):
            if a[i] > a[k]:
                b += 1
        d1[i] = b
    ans = 0
    d2 = list(d0.items())
    d2.sort()
    d3 = defaultdict(int)
    d = 0
    for key, value in d2:
        d3[key] = d
        d += value
    for i in range(n):
        ans += d3[a[i]] * l * (l-1) // 2 + d1[i] * l
        ans %= mod
    print(ans % mod)
    return

#C
def C():
    n = II()
    s = S()
    lis = [0]
    for i in range(2 * n - 1):
        lis.append(lis[-1] ^ (s[i] == s[i+1]))
    l = [0] * (2 * n)
    for i in range(2 * n):
        l[i] += l[i - 1] + (lis[i] == 0)
    ans = 1
    if l[-1] != n or s[0] == "W":
        print(0)
        return
    k = 1
    for i in range(2 * n):
        if lis[i]:
            ans *= l[i] - (k - 1)
            ans %= mod
            k += 1
    print(ans * math.factorial(n) % mod)
    return

#D
def D():
    return

#E
def E():
    return

#F
def F():
    return

#G
def G():
    return

#H
def H():
    return

#Solve
if __name__ == '__main__':
    C()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import *
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def LS(): return list(map(list, input().split()))
def S(): return list(input().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')

#A
def A():
    m, d = LI()
    ans = 0
    for i in range(1, m + 1):
        for j in range(10, d + 1):
            if int(str(j)[0]) < 2 or int(str(j)[1]) < 2:
                continue
            if i == int(str(j)[0]) * int(str(j)[1]):
                ans += 1
    print(ans)
    return

#B
def B():
    n, l = LI()
    a = LI()
    d0 = defaultdict(int)
    d1 = defaultdict(int)
    for i in a:
        d0[i] += 1
    for i in range(n):
        b = 0
        for k in range(i+1, n):
            if a[i] > a[k]:
                b += 1
        d1[i] = b
    ans = 0
    d2 = list(d0.items())
    d2.sort()
    d3 = defaultdict(int)
    d = 0
    for key, value in d2:
        d3[key] = d
        d += value
    for i in range(n):
        ans += d3[a[i]] * l * (l-1) // 2 + d1[i] * l
        ans %= mod
    print(ans % mod)
    return

#C
def C():
    n = II()
    s = S()
    lis = [0]
    for i in range(2 * n - 1):
        lis.append(lis[-1] ^ (s[i] == s[i+1]))
    l = [0] * (2 * n)
    r = [0] * (2 * n)
    for i in range(2 * n):
        l[i] += l[i - 1] + (lis[i] == 0)
        r[i] += r[i - 1] + (lis[i] == 1)
    ans = 1
    if l[-1] != r[-1] or s[0] == "W":
        print(0)
        return
    for i in range(2 * n):
        if lis[i]:
            ans *= l[i] - (r[i] - 1)
            ans %= mod
    print(ans * math.factorial(n) % mod)
    return

#D
def D():
    return

#E
def E():
    return

#F
def F():
    return

#G
def G():
    return

#H
def H():
    return

#Solve
if __name__ == '__main__':
    C()

Submission status: Accepted

Solution code:
def main():
    md = 10 ** 9 + 7
    n = int(input())
    s = input()
    a = [c == "B" for c in s]
    B = True
    W = False
    a = [b if i % 2 else not b for i, b in enumerate(a)]
    if sum(a) != n:
        print(0)
        exit()
    ans = 1
    cnt_W = 0
    for b in a:
        if b == W:
            cnt_W += 1
        else:
            ans = (ans * cnt_W) % md
            cnt_W -= 1
            if ans == 0:
                print(0)
                exit()
    fac_n = 1
    for i in range(1, n + 1):
        fac_n = (fac_n * i) % md
    print((ans * fac_n) % md)

main()

Submission status: Accepted

Solution code:
from functools import reduce
n = int(input())
s = list(input())
def count_combination(x):
    if sum(x) != n:
        return(0)
    total_count = 1
    false_count = 0
    for i in range(2*n):
        if x[i]:
            total_count = total_count*false_count%(10**9+7)
            false_count -= 1
        else:
            false_count += 1
        if false_count == -1:
            return(0)
    return(total_count)
sb = list(map(lambda x: False if x == 'W' else True, s))
sb[::2] = list(map(lambda x: not x, sb[::2]))

total_count = count_combination(sb)

permutation = reduce(lambda x, y: x*y%(10**9+7), range(1,n+1))

print(total_count * permutation % (10**9+7))

Submission status: Accepted

Solution code:
"""
https://atcoder.jp/contests/jsc2019-qual/tasks/jsc2019_qual_c

B -> 1
W -> 0

BWWWWB
100001

反転操作を３つに分解
左端からl-1まで+1
左端からr-1まで+1
rに+1

こうしておくとつまり、右端として選ぶかどうかを決めるだけでよくなる

"""

from math import factorial

N = int(input())
d = {"W":0, "B":1}
ls = [d[s] for s in input()]
r_ls = reversed(ls)
xs = []
mod = 10**9 + 7
# 全部左右とか関係なく取ったとする
for i,r in enumerate(r_ls):
    xs.append(r + i)
# 右でトルものを選ぶ(↑の操作後、mod2が1のところ)
LR = [x%2 for x in list(reversed(xs))]

# Lの数を持ちながら、Rが来たら消化＆場合の数にLの数をかける
cnt = 0 # Lの数
num = 1 # 場合の数

for lr in LR:
    if lr == 0:
        cnt += 1
    else:
        num *= cnt
        cnt -= 1
        cnt = max(0,cnt)
        num %= mod
# LとRのペアが一致していない
if cnt > 0:
    num = 0
ans = num * factorial(N)
print(ans%mod)

Submission status: Accepted

Solution code:
import math

n = int(input())
s = input()
s2 = list(s)

if s[0] == 'B':
    s2[0] = 'L'
else:
    s2[0] = 'R'

for i in range(1,2*n): 
    if s[i-1] == s[i]:
        if s2[i-1] == 'L':
            s2[i] = 'R'
        else:
            s2[i] = 'L'
    else:
        if s2[i-1] == 'L':
            s2[i] = 'L'
        else:
            s2[i] = 'R'
        
if s2[0] == 'R' or s2[2*n-1] == 'L' or s2.count('L') != s2.count('R'):
    print(0)
    exit()
            
ans = 1
count_l = 0
for s2_str in s2: 
    if s2_str == 'L':
        count_l += 1
    else:
        ans *= count_l
        ans %= 10**9 + 7
        count_l -= 1
    
print(ans * math.factorial(n) % (10**9 + 7))

Submission status: Accepted

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

MOD = 10 ** 9 + 7

N = int(input())
S = list(map(lambda x: int(x == "W"),input()))
if S[0] or S[-1]:
    print(0)
    exit(0)

Dc = 1
LRsub = 1
Pattern = 1
Sp = S[0]

for i in range(1,N*2):
    Sc = S[i]
    Dc = Dc if Sc != Sp else -Dc
    Sp = Sc
    if Dc < 0:
        Pattern = (Pattern * LRsub) % MOD
    LRsub += Dc

if LRsub == 0:
    for i in range(2,N+1):
        Pattern = (Pattern * i) % MOD
    print(Pattern)
else:
    print(0)

Submission status: Accepted

Solution code:
import sys
M = 10**9 + 7
n = int(input()) * 2
s = list(map(lambda x: int(x == "W"), input()))

lr = [0] * n # L: 0, R: 1

if s[0] or s[-1]:
    print(0)
    sys.exit()

l = 1
ans = 1
for i, v in enumerate(s[1:], 1):
    if v:
        if l % 2:
            l += 1
        else:
            ans *= l
            l -= 1
            lr[i] = 1
    else:
        if l % 2 == 0:
            l += 1
        else:
            ans *= l
            l -= 1
            lr[i] = 1
    if ans > M:
        ans %= M
    if l < 0:
        print(0)
        sys.exit()

if not lr[-1] or l:
    print(0)
    sys.exit()

def fact(n):
    result = 1
    for i in range(2, n + 1):
        result *= i
        if result > M:
            result %= M
    return result
print((ans * fact(n // 2)) % M)

Submission status: Accepted

Solution code:
import sys, math, itertools, bisect, copy, re

from collections import Counter, deque, defaultdict
from itertools import accumulate, permutations, combinations, takewhile, compress, cycle
from functools import reduce
from math import ceil, floor, log10, log2, factorial
from pprint import pprint

# 10倍速いらしい
input = sys.stdin.readline

INF = float('inf')
MOD = 10 ** 9 + 7
EPS = 10 ** -7
sys.setrecursionlimit(1000000)

# N = int(input())
# N,M = [int(x) for x in input().split()]
# V = [[0] * 100 for _ in range(100)]
# A = [int(input()) for _ in range(N)]
# DP = [[0] * 100 for _ in range(100)]
# DP = defaultdict(lambda: float('inf'))

N = int(input())
S = input().strip()
L = [0] * 2 * N
D = []

cnt = 1
D.append('L')
L = [cnt]
for i, s in enumerate(S):
    if i == 0:
        continue
    if s == 'W':
        if cnt % 2 == 1:
            cnt += 1
            D.append('L')
        else:
            cnt -= 1
            D.append('R')
    else:
        if cnt % 2 == 1:
            cnt -= 1
            D.append('R')
        else:
            cnt += 1
            D.append('L')
    L.append(cnt)

if len(list(filter(lambda x: x < 0, L))) > 0 or L[-1] != 0:
    print(0)
    sys.exit()

ans = 1
for i in range(1, 2 * N):
    if D[i] == 'R':
        ans *= L[i - 1]
        ans %= MOD

for i in range(1, N + 1):
    ans *= i
    ans %= MOD

print(ans)

# print(D)
# print(L)

Submission status: Accepted

Solution code:
n = int(input())
S = [v for v in input()]

# determine L or R
lst = [0 for i in range(2 * n)]
for i in range(2 * n):
    if S[i] == 'W' and (2 * n - i - 1) % 2 == 0:
        lst[i] = 'L'
    elif S[i] == 'W' and (2 * n - i - 1) % 2 == 1:
        lst[i] = 'R'
    elif S[i] == 'B' and (2 * n - i - 1) % 2 == 0:
        lst[i] = 'R'
    elif S[i] == 'B' and (2 * n - i - 1) % 2 == 1:
        lst[i] = 'L'


deq = 0
val = 1
#tracing lst
for i in range(2 * n):
    if lst[i] == 'L':
        deq += 1
    elif lst[i] == 'R':
        val *= deq
        val %= 10 ** 9 + 7
        deq -= 1

if deq != 0:
    print(0)
else:
    for i in range(1, n + 1):
        val = val * i % (10 ** 9 +7)
    print(val)

Submission status: Accepted

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

if S[0] == 'W' or S[-1] == 'W':
    print (0)
    exit()

lst = [0] * (2 * N + 1)
ans = [-1] * (2 * N + 1) #左で選んだ時1, 右で選んだ時0
lst[0] = 1
ans[0] = 1
for i in range(1, 2 * N):
    if S[i] == 'B': #奇数にする必要
        if (lst[i - 1] + lst[i]) % 2 == 0: #前が偶数
            lst[i] += lst[i - 1] + 1
            ans[i] = 1
        else: #前が奇数
            lst[i] += lst[i - 1]
            lst[i + 1] -= 1
            ans[i] = 0

    if S[i] == 'W': #偶数にする必要
        if (lst[i - 1] + lst[i]) % 2 == 0: #前が偶数
            lst[i] += lst[i - 1]
            ans[i] = 0
            lst[i + 1] -= 1
        else: #前が奇数
            lst[i] += lst[i - 1] + 1
            ans[i] = 1

count = 1
tmp = 0
for i in range(2 * N - 1, -1, -1):
    if ans[i] == 0:
        tmp += 1
    else:
        count *= tmp
        count %= MOD
        tmp -= 1
if tmp != 0:
    print (0)
    exit()
    
count *= math.factorial(N)
print (count % MOD)

Submission status: Accepted

Solution code:
def resolve():
    n = int(input())
    s_list = list(input())
    mod = 10 ** 9 + 7

    if s_list[0] == "W" or s_list[-1] == "W":
        print(0)
        return

    from math import factorial

    l_counter = 0
    res = 1

    for i in range(2 * n):
        s = s_list[i]
        if i % 2 == 0:
            s = "W" if s == "B" else "B"

        if s == "W":
            l_counter += 1
        else:
            res = res * l_counter % mod
            l_counter -= 1
            if l_counter < 0:
                print(0)
                return

    if l_counter != 0:
        print(0)
    else:
        print(res * factorial(n) % mod)
        
resolve()

Submission status: Accepted

Solution code:
import math

n = int(input())
s = list(input())
mod = 10**9+7

cnt_w = 0
cnt_ans = 1

for i in range(0,n*2):
    if i%2 == 0:
        if s[i] == "B":
            s[i] = "W"
        else:
            s[i] = "B"
    if s[i] == "W":
        cnt_w += 1
        continue
    if s[i] == "B":
        cnt_ans *= cnt_w
        cnt_w -= 1
        cnt_ans %= mod

if s.count("B") != s.count("W"):
    print(0)
    exit()
    
print((cnt_ans*math.factorial(n))%mod)

Submission status: Accepted

Solution code:
MOD = 10**9 + 7

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

is_left = [(i%2 == 0) ^ (x == "W") for i, x in enumerate(S)]

answer = 1
left = 0
for bl in is_left:
    if bl:
        left += 1
    else:
        answer *= left
        left -= 1
        answer %= MOD

if left != 0:
    answer = 0
    
for i in range(1, N+1):
    answer *= i
    answer %= MOD

print(answer)

Submission status: Accepted

Solution code:
import math
n = int(input())
s = [0 if i == "W" else 1 for i in list(input())]
cnt = 0
c = 1
for i in range(n * 2):
    if (s[i] + cnt) % 2 != 0:
        cnt += 1
    else:
        c = (c * (cnt if cnt != 0 else 1)) % (10 ** 9 + 7)
        cnt -= 1
    if cnt < 0:
        print(0)
        exit()
if cnt != 0:
    print(0)
else:
    print((c * math.factorial(n)) % (10 ** 9 + 7))

Submission status: Accepted

Solution code:
mod=10**9+7
n=int(input())
s=list(input())
#前処理
for i in range(0,2*n,2):
    if s[i]=='W':
        s[i]='B'
    else:
        s[i]='W'

#Lの数を数えてRとマッチング
countL=0
ans=1
for i in range(2*n):
    if s[i]=='W':
        countL+=1
    else:
        ans*=countL
        if countL==0:
            print(0)
            exit()
        ans%=mod
        countL-=1
if countL!=0:
    print(0)
    exit()
# 答えはansの階乗
for i in range(1,n+1):
    ans*=i
    ans%=mod
print(ans)

Submission status: Accepted

Solution code:
import sys
import heapq
from operator import itemgetter
from collections import deque, defaultdict, Counter
from bisect import bisect_left, bisect_right
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)
MOD = 10**9 + 7

def sol():
    N = int(input())
    S = input().rstrip()

    isLeft = [(i % 2 == 0) ^ (s == 'W') for i, s in enumerate(S)]

    ans = 1
    left = 0
    for black in isLeft:
        if black:
            left += 1
        else:
            ans = (ans * left) % MOD
            left -= 1

    if left != 0:
        ans = 0

    for i in range(1, N + 1):
        ans = (ans * i) % MOD

    print(ans)

sol()

Submission status: Accepted

Solution code:


import sys
def input():
	return sys.stdin.readline().strip()

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

LR = ['L', 'R']
if S[0] != "B" or S[-1] != "B":
	print(0)
	exit()
x = [0]
for i in range(1, 2*N):
	if S[i] == S[i - 1]:
		x.append(x[-1]^1)
	else:
		x.append(x[-1])

if x[-1] != 1:
	print(0)
	exit()
if sum(x) != N:
	print(0)
	exit()

L_sum = 0
total = 1
for i in range(0, 2*N):
	if x[i] == 0:
		L_sum += 1
	else:
		total *= L_sum
		L_sum -=1
		total = total % 1000000007

for i in range(N):
	total *= i + 1
	total = total % 1000000007

print(total)

Submission status: Accepted

Solution code:
import math
N = int(input())
S = input()
mod = 10**9+7
if(not (S[0]==S[-1]=='B')):
    print(0)
else:
    d = []
    cumu = [[0]*2 for _ in range(N*2)]
    cnt = 1
    for ind,s in enumerate(S):
        if(ind==0):
            d.append(0)
            cumu[0][0]+=1
        else:
            if(S[ind-1]==s):
                d.append(1-d[-1])
            else:
                d.append(d[-1])
            cumu[ind][0] = cumu[ind-1][0]
            cumu[ind][1] = cumu[ind-1][1]
            cumu[ind][d[-1]]+=1
            if(d[-1]==1):
                cnt *= (cumu[ind-1][0]-cumu[ind-1][1])
                cnt %= mod
    if(cumu[-1][0]!=cumu[-1][1]):
        cnt=0
    print((math.factorial(N)*cnt)%mod)

Submission status: Accepted

Solution code:
n = int(input())
s = input()
mod = 10**9+7
dp = []
imos = [0 for _ in range(n*2+1)]
now = 0
for i in range(n*2):
    c = 1 if s[i]=='B' else 0
    if c==now%2:
        imos[i]-=1
        dp.append(-1)
    else:
        imos[i]+=1
        dp.append(1)
    now+=imos[i]
if sum(dp)!=0:
    print(0)
    exit()
ans = 1
cnt = 0
for i in dp:
    if i==1:
        cnt+=1
    else:
        ans*=cnt
        ans%=mod
        cnt-=1
for i in range(1,n+1):
    ans*=i
    ans%=mod
print(ans)

Submission status: Accepted

Solution code:
n,s=open(0)
a=i=1
l=0
for c in s:f=(c>'B')^i%2;l+=f or-1;a=a*l**f*(i>int(n)or i)%(10**9+7);i+=1
print(a*(l==1))

Submission status: Accepted

Solution code:
n,s=open(0)
a=i=1
l=0
for c in s:f=(c>'B')^i%2;l+=f;a=a*l**f*(i>int(n)or i)%(10**9+7);l-=f^1;i+=1
print(a*(l==1))

Submission status: Accepted

Solution code:
n,s=open(0)
a=i=1
l=0
for c in s[:-1]:f=(c>'B')^i%2;l+=f;a=a*l**f*(i>int(n)or i)%(10**9+7);l-=f^1;i+=1
print(a*(l==0))

Submission status: Accepted

Solution code:
n,s=open(0)
a=i=1
l=0
for c in s[:-1]:f=(c>'B')!=i%2;l+=f;a=a*l**f*(i>int(n)or i)%(10**9+7);l-=f^1;i+=1
print(a*(l==0))

Submission status: Accepted

Solution code:
n,s=open(0)
a=1
l=0
for i,c in enumerate(s[:-1]):f=(c>'B')==i%2;l+=f;a=a*l**f*(i>=int(n)or-~i)%(10**9+7);l-=f^1
print(a*(l==0))

Submission status: Accepted

Solution code:
n,s=open(0)
n=int(n)
a=l=s[0]<'W'>s[-2]
r=f=0
for b,c in zip(s,s[1:-1]):f^=b==c;a=a*(n<1or n)*(l-r)**f%(10**9+7);n-=1;r+=f;l+=f^1
print(a*(l==r))

Submission status: Accepted

Solution code:
n,s=open(0)
n=int(n)
a=l=s[0]<'W'>s[-2]
r=f=0
for b,c in zip(s,s[1:-1]):f^=b==c;a=a*(max(1,n))*(l-r)**f%(10**9+7);n-=1;r+=f;l+=f^1
print(a*(l==r))

Submission status: Accepted

Solution code:
N = int(input())
S = input()
count = 0
ans = 1
m = 10**9 + 7
 
for i in range(N):
  if S[2*i] == "W":
    ans = (ans * ((2*i) - (count*2)))%m
    count += 1
  if S[2*i + 1] == "B":
    ans = (ans * ((2*i + 1) - (count*2)))%m
    count += 1
 
if count != N:
  print(0)
else:
  for o in range(1, N+1):
    ans *= o
    ans %= m
  print(ans % m)

Submission status: Accepted

Solution code:
n,s=open(0)
n=int(n)
a=l=s[0]<'W'>s[-2]
r=f=0
for b,c in zip(s,s[1:-1]):
 if n:a*=n;n-=1
 f^=b==c;a=a*(l-r)**f%(10**9+7);r+=f;l+=f^1
print(a*(l==r))

Submission status: Accepted

Solution code:
import math
n = int(input())
s = [0 if i == "W" else 1 for i in list(input())]
cnt = 0
c = 1
for i in range(n * 2):
    if (s[i] + cnt) % 2 != 0:
        cnt += 1
    else:
        c = (c * (cnt if cnt != 0 else 1)) % (10 ** 9 + 7)
        cnt -= 1
    if cnt < 0:
        print(0)
        exit()
if cnt != 0:
    print(0)
else:
    print((c * math.factorial(n)) % (10 ** 9 + 7))

Submission status: Accepted

Solution code:
N = int(input())
S = input()
MOD = 10**9+7
TO_INT = {'B': 1, 'W': -1}
BW = S[:]
BW = [TO_INT[s] for s in BW]

if BW[0] == -1 or BW[-1] == -1:
    print(0)
else:
    LR = [1] # {'L': 1, 'R': -1}
    for i in range(1, 2*N):
        if BW[i-1] != BW[i]:
            LR.append(LR[i-1])
        else:
            LR.append(-1*LR[i-1])
    if sum(LR) != 0:
        print(0)
    elif LR[-1] == 1:
        print(0)
    else:
        cnt = 0
        ans = 1
        for n in LR:
            if n == 1:
                cnt+=1
            else:
                ans = ans * cnt % MOD
                cnt -= 1
        import math
        print(ans*math.factorial(N)% MOD)

Submission status: Accepted

Solution code:
N = int(input())
S = input()
count = 0
ans = 1
m = 10**9 + 7
 
for i in range(N):
  if S[2*i] == "W":
    ans = ans * ((2*i) - (count*2))%m
    count += 1
  if S[2*i + 1] == "B":
    ans = ans * ((2*i + 1) - (count*2))%m
    count += 1
 
if count != N:
  print(0)
else:
  for o in range(1, N+1):
    ans *= o
    ans %= m
  print(ans % m)

Submission status: Accepted

Solution code:
M=10**9+7
n,s=open(0)
n=int(n)
a=l=s[0]<'W'>s[-2]
r=f=0
for b,c in zip(s,s[1:-1]):f^=b==c;a=a*(l-r)**f%M;r+=f;l+=f^1
while n:a=a*n%M;n-=1
print(a*(l==r))

Submission status: Accepted

Solution code:
M=10**9+7
n,s=open(0)
n=int(n)
a=s[0]<'W'>s[-2]
while n:a=a*n%M;n-=1
l=1
r=f=0
for b,c in zip(s,s[1:-1]):f^=b==c;a=a*(l-r)**f%M;r+=f;l+=f^1
print(a*(l==r))

Submission status: Accepted

Solution code:
def main():
    import sys
    def input():
        return sys.stdin.readline()[:-1]

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

    if S[0]!='B' or S[-1]!='B':
        print(0)
        exit()

    mod = 10**9 + 7
    cnt = 1
    pre = 'B'
    d = 1 #1がleft
    ans = 1

    for i in range(1,N*2):
        if S[i-1]==S[i]:
            if d:
                d = 0
                ans *= cnt
                ans %= mod
                cnt -= 1
            else:
                d = 1
                cnt += 1
        else:
            if d:
                cnt += 1
            else:
                ans *= cnt
                ans %= mod
                cnt -= 1

    for i in range(1,N+1):
        ans *= i
        ans %= mod
    if cnt!=0:
        print(0)
        exit()

    print(ans)

if __name__=='__main__':
    main()

Submission status: Accepted

Solution code:
import sys
n=int(input())
s=list(input())
m=10**9+7
if s[0]=='W' or s[2*n-1]=='W':
  print(0)
  sys.exit()
side=[]
l=['L','R']
for i in range(2*n):
  if i==0:
    side.append('L')
  else:
    if s[i-1]==s[i]:
      side.append(l[(l.index(side[i-1])+1)%2])
    else:
      side.append(l[l.index(side[i-1])])
ctL=0;ctR=0;ans=1
for i in range(2*n):
  if side[i]=='L':
    ctL+=1
  else:
    ans=ans*(ctL-ctR)
    ans%=m
    ctR+=1
if ctL!=ctR:
  print(0)
  sys.exit()
for i in range(1,n+1):
  ans*=i
  ans%=m
print(ans)

Submission status: Accepted

Solution code:
import math
n = int(input())
S = input()
 
RL = [None]*2*n
 
for i in range(2*n):
    if i % 2 == 0:
        if S[i] == 'B':
            RL[i] = 'L'
        else:
            RL[i] = 'R'
 
    else:
        if S[i] == 'B':
            RL[i] = 'R'
        else:
            RL[i] = 'L'
 
if S[0] == 'W' or S[-1] == 'W':
    print(0)
    exit()
 
left = 0
count = 1
mod = 10**9 + 7
 
for check in RL:
    if check == 'L':
        left += 1
    else:
        count = count * left % mod
        left -= 1
 
    if left < 0:
        print(0)
        exit()
 
count = count * math.factorial(n) % mod
 
if left != 0:
    print(0)
else:
    print(count)

Submission status: Accepted

Solution code:
import math
n = int(input())
S = input()

RL = [None]*2*n

for i in range(2*n):
    if i % 2 == 0:
        if S[i] == 'B':
            RL[i] = 'L'
        else:
            RL[i] = 'R'

    else:
        if S[i] == 'B':
            RL[i] = 'R'
        else:
            RL[i] = 'L'

if S[0] == 'W' or S[-1] == 'W':
    print(0)
    exit()

left = 0
count = 1
mod = 10**9 + 7

for check in RL:
    if check == 'L':
        left += 1
    else:
        count = count * left % mod
        left -= 1

    if left < 0:
        print(0)
        exit()

count = count * math.factorial(n) % mod

if left != 0:
    print(0)
else:
    print(count)

Submission status: Accepted

Solution code:
import math
import sys
from copy import copy
import numpy as np
from collections import defaultdict, deque, Counter 
from itertools import accumulate, product, permutations,combinations, combinations_with_replacement
from operator import itemgetter
from bisect import bisect_left,bisect
from heapq import heappop,heappush
from fractions import gcd

max_value = 1000000000
min_value = -1000000000
sys.setrecursionlimit(max_value)

n = int(input())
s = list(input())

count = 0


if s[0] == 'W' or s[-1] == 'W':
    print(0)
    sys.exit()

LR_list = ['' for i in range(2*n)]
LR_list[0] = 'L'

for i in range(1,len(LR_list)):
    if s[i] == s[i-1]:
        if LR_list[i-1] == 'R':
            LR_list[i] = 'L'
        else:
            LR_list[i] = 'R'
    else:
        if LR_list[i-1] == 'R':
            LR_list[i] = 'R'
        else:
            LR_list[i] = 'L'

values = []

if LR_list.count('L') != LR_list.count('R'):
    print(0)
    sys.exit()


li = 0
ri = 0
for i in range(len(LR_list)):
    if i != 0:
        if LR_list[i-1] == 'L':
            li += 1
        elif LR_list[i-1] == 'R':
            ri += 1
    if LR_list[i] == 'R':
        values.append(li-ri)
value = 1
for i in range(len(values)):
    value = value * values[i] % (10**9+7)
for i in range(2,n+1):
    value = value * i %(10**9+7)
print(value)