Problem:


Score : 400 points

Problem Statement

An altar enshrines N stones arranged in a row from left to right. The color of the i-th stone from the left (1 \leq i \leq N) is given to you as a character c_i; R stands for red and W stands for white.

You can do the following two kinds of operations any number of times in any order:

Choose two stones (not necessarily adjacent) and swap them.

Choose one stone and change its color (from red to white and vice versa).

According to a fortune-teller, a white stone placed to the immediate left of a red stone will bring a disaster. At least how many operations are needed to reach a situation without such a white stone?

Constraints

2 \leq N \leq 200000

c_i is R or W.

Input

Input is given from Standard Input in the following format:

N
c_{1}c_{2}...c_{N}

Output

Print an integer representing the minimum number of operations needed.

Sample Input 1

4
WWRR

Sample Output 1

2

For example, the two operations below will achieve the objective.

Swap the 1-st and 3-rd stones from the left, resulting in RWWR.

Change the color of the 4-th stone from the left, resulting in RWWW.

Sample Input 2

2
RR

Sample Output 2

0

It can be the case that no operation is needed.

Sample Input 3

8
WRWWRWRR

Sample Output 3

3



Sample input:
4
WWRR


Sample output:
2

Submission status: Accepted

Solution code:
def resolve():
    n = int(input())
    c = input()
    ans = 0
    l = -1
    r = n
    while True:
        l += 1
        r -= 1
        while l < n and c[l] == "R":
            l += 1
        while r >= 0 and c[r] == "W":
            r -= 1
        if l > r:
            break
        ans += 1
    print(ans)


if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
N = int(input())
string = input()
r2w = string.count("R")
w2r = 0
ans_list = [max(r2w, w2r)]
for c in string:
    if c == "W":
        w2r += 1
    else:
        r2w -= 1
    ans_list.append(max(r2w, w2r))
print(min(ans_list))

Submission status: Accepted

Solution code:
N, = map(int, input().split())
X = input().strip()
i,j = 0,N-1
R = 0
while i<=j:
    if X[i] == "R":
        i += 1
        continue
    if X[j] == "W":
        j -= 1
        continue
    R += 1
    i += 1
    j -= 1
print(R)

Submission status: Accepted

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

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n = I()
c = input()
d = c.count('R')
ans = d
for i in range(d):
    if c[i] == 'R':
        ans -= 1
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
s = input()
cur = [0, 0]
pref = []
for i in range(n):
	if s[i] == 'W':
		cur[0] += 1
	else:
		cur[1] += 1
	pref += [cur[:]]

# print(pref)

res = min(pref[-1][0], pref[-1][1])
for i in range(1, n):
	# print(i, res)
	rem = i - pref[i-1][1]
	ans = rem
	# print('a', ans, rem)

	rightred = pref[-1][1] - pref[i-1][1]

	if rightred >= rem:
		ans += rightred-rem
	else:
		ans += rem-rightred

	res = min(res, ans)

print(res)

Submission status: Accepted

Solution code:
import sys
def input(): return sys.stdin.readline().strip()
# sys.setrecursionlimit(100000)


def main():
    N = int(input())
    S = input()

    table = [0] * (N + 1)

    if len(set(S)) == 1:
        print(0)
        return
    # 赤の累積和

    for i in range(1, N + 1):
        if S[i - 1] == "R":
            table[i] = table[i - 1] + 1
        else:
            table[i] = table[i - 1]

    ans = float("inf")

    for i in range(N):
        left_red = table[i]
        left_white = i - table[i]
        right_red = table[N] - table[i]
        right_white = N - i - right_red
        # print(left_red, left_white, right_red, right_white)
        ans = min(ans, max(left_white, right_red))

    print(ans)
    return


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# D

n = int(input())
c_l = input()

ans = 0
l = 0
r = n
while True:
    _l = c_l.find("W", l, n-1)
    _r = c_l.rfind("R", 0, r)
    if _l >= _r or _l == -1 or _r == -1:
        break
    ans += 1
    l = _l + 1
    r = _r

print(ans)

Submission status: Accepted

Solution code:
N = int(input())
C = input()
cnt = 0
left = 0
right = N-1
while(left < right and left<=N-1):
  if(C[left] == 'W'):
    flag = 0
    while(left < right):
      if(C[right] == 'R'):
        cnt += 1
        right -= 1
        break
      right -= 1
  left += 1
print(cnt)

Submission status: Accepted

Solution code:
n = int(input())
c = input()
count = 0
for i in range(n):
    if c[i] == "R":
        count += 1
count2 = 0
for i in range(count):
    if c[i] == "R":
        count2 += 1
print(count - count2)

Submission status: Accepted

Solution code:
n=int(input())
c=input()
if "R" not in c or "W" not in c:print(0);exit()
rcnt=[0]*(n+1)
wcnt=[0]*(n+1)
for i in range(n):
    if c[i]=="W":
        wcnt[i+1]=wcnt[i]+1
        rcnt[i+1]=rcnt[i]
    else:
        rcnt[i+1]=rcnt[i]+1
        wcnt[i+1]=wcnt[i]
ans=n+100
for i in range(n):
    cw=wcnt[i+1]
    cr=rcnt[-1]-rcnt[i+1]
    ans=min(ans,cw+cr-min(cr,cw))
ans=min(ans,wcnt[-1])
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
C = input()

cntR = C.count('R')
cntW = C.count('W')
if cntR == 0 or cntW == 0:
    print(0)
else:
    T = 'R' * cntR + 'W' * cntW
    ans = sum([1 for a, b in zip(C, T) if a != b]) // 2
    print(ans)

Submission status: Accepted

Solution code:
def main():
    N = int(input())
    C = list(input())
    ans = 0
    red = C.count('R')
    white = C.count('W')
    # 左に赤、右に白を寄せる場合
    cnt = 0
    for i in range(red):
        if C[i] == 'W':
            cnt += 1

    print(cnt)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n = int(input())
c = list(input())
r = c.count('R')
r2 = c[:r].count('R')
print(r - r2)

Submission status: Accepted

Solution code:
n=int(input())
C=input()
rc=C.count('R')
x=C.count('R',0,rc)
print(rc-x)

Submission status: Accepted

Solution code:
n = int(input())
c = list(input())
w, r = [0] * (n + 1), [0] * (n + 1)
for i in range(n):
    if c[i] == "W":
        w[i + 1] = w[i] + 1
        r[i + 1] = r[i]
    else:
        w[i + 1] = w[i]
        r[i + 1] = r[i] + 1
ans = min(w[n], r[n])
for i in range(1, n):
    x = w[i] - w[0]
    y = r[n] - r[i]
    ans = min(ans, x + abs(x - y))
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
color = list(input())

left = 0
right = N-1

ans = 0

while left < right:
    while color[left] == "R":
        left += 1
        if left >= N:
            break

    while color[right] == "W":
        right -= 1
        if right < 0:
            break
    
    if left < right:
        ans += 1
        left += 1
        right -= 1

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
c = input()
r = c.count('R')
w = c.count('W')
print(c[:r].count('W'))

Submission status: Accepted

Solution code:
n = int(input())
stones = input()

t = stones.count('R')

num_not_equal = t
red_num_diff = t
red_count = 0

ans = t
for s in stones:
    if s == 'R':
        num_not_equal -= 1
    else:
        num_not_equal += 1

    red_count += 1
    red_num_diff = abs(red_count - t)

    temp = red_num_diff + (num_not_equal - red_num_diff) // 2
    ans = min(ans, temp)

    # print(num_not_equal, red_num_diff)

print(ans)

Submission status: Accepted

Solution code:
def main():
    n = int(input())
    c = input()
    w = c.count("W")
    ans = 0
    r = n - w
    for i in range(n):
        target = "R" if i < r else "W"
        if c[i] != target:
            ans += 1
    print(min(ans // 2, w, r) if 0 < w < n else 0)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n = int(input())
c = input()

count_r = 0
count_w = 0
R = []
W = []
for i in range(n):
    if c[i:i+1] == "R":
        count_r += 1
        R.append(i)
    else:
        count_w += 1
        W.append(i)

ans_count = 0
while count_r * count_w:
    if  ans_count+1 > count_r or ans_count+1 > count_w:
        break
    if R[-(1+ans_count)] < W[ans_count]:
        break
    ans_count += 1

print(min(ans_count,count_r,count_w))

Submission status: Accepted

Solution code:
N = int(input())
C = input()
W = C.count('W')
a = C[N-W:N].count('W')
print(W-a)

Submission status: Accepted

Solution code:
n = int(input())
c = input()
r = c.count("R")
w = 0
a = r
for ci in c:
    if ci == "R":
        r -= 1
    elif ci == "W":
        w += 1
    a = min(max(w, r), a)
print(a)

Submission status: Accepted

Solution code:
#d
n=int(input())
c=input()
rr=c.count('R')
ans=0
for i in range(rr):
    if c[i]=='W':
        ans+=1
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
c=input()

W=0
R=0

for i in range(n):
    if c[i]=="W":
        W+=1
    if c[i]=="R":
        R+=1

leftW=0
for i in range(R):
    if c[i]=="W":
        leftW+=1

print(leftW)

Submission status: Accepted

Solution code:
n=int(input())
lc=list(input())
r=lc.count("R")
w=lc.count("W")

l=["R" for i in range(r)]+["W" for i in range(w)]

p=0
q=0
for i in range(r):
    if l[i]!=lc[i]:
        p+=1
for i in range(w):
    if l[r+i]!=lc[r+i]:
        q+=1
m=max(p,q)
print(min(m,r,w))

Submission status: Accepted

Solution code:
def main():
    N = int(input())
    C = list(input())
    ans = 0
    w, r = 0, N - 1
    while True:
        while w < N and C[w] != 'W':
            w += 1
        if w == N:
            break
        while r >= 0 and C[r] != 'R':
            r -= 1
        if r == -1:
            break
        if r < w:
            break
        C[w] = 'R'
        C[r] = 'W'
        ans += 1
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n = int(input())
C = input()
chk = 0
for i in range(n):
    if C[n-1-i] == 'R':
        chk = n-1-i
        break
cnt = 1
for i in range(chk):
    if C[i] == 'R':
        cnt += 1
ans = 0
for i in range(cnt):
    if C[i] == 'W':
        ans += 1
if 'R' not in C:
    print(0)
else:
    print(ans)

Submission status: Accepted

Solution code:
n=int(input())
s=input()
cr=0
for i in range(n):
    if s[i]=="R":
        cr+=1
ans=0
for i in range(cr):
    if s[i]=="W":
        ans +=1
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
C = input()

red = C.count('R')
white = C.count('W')

left = C[:red]
ans = left.count('W')

print(ans)

Submission status: Accepted

Solution code:
N = int(input())
S = input()
WPrefix = [0]
RSuffix = [0]
for elem in S:
    if elem == "R":
        RSuffix[0] += 1
for elem in S:
    if elem == "R":
        RSuffix.append(RSuffix[-1] - 1)
        WPrefix.append(WPrefix[-1])
    else:
        RSuffix.append(RSuffix[-1])
        WPrefix.append(WPrefix[-1] + 1)
minSwap = len(S)
for index in range(len(RSuffix)):
    if max(RSuffix[index],WPrefix[index]) < minSwap:
        minSwap = max(RSuffix[index],WPrefix[index])
print(minSwap)

Submission status: Accepted

Solution code:
from collections import Counter

(N,) = [int(x) for x in input().split()]
S = list(input())
freq = Counter(S)
count = 0
for i in range(freq["R"]):
    if S[i] != "R":
        count += 1
print(count)

Submission status: Accepted

Solution code:
N = int(input())
C = input()

r = 0
w = 0

for i in range(N):
    if C[i] == 'R':
         r += 1
    else:
         w += 1

s = 0

for i in range(r):
    if C[i] == 'W':
        s += 1

print(s)

Submission status: Accepted

Solution code:
def main():
  n = int(input())
  s =  str(input())
  num_r = 0
  for i in range(n):
    if s[i] == "R":
      num_r += 1
  ans = 0
  for i in range(num_r):
    if s[i] == "W":
      ans += 1
  print(ans)

if __name__ == "__main__":
  main()

Submission status: Accepted

Solution code:
N = int(input())
c = list(input())

iRs = []
iWs = []
for i in range(N):
    i_inv = N - 1 - i
    if c[i] == 'W':
        iWs.append(i)
    if c[i_inv] == 'R':
        iRs.append(i_inv)
iRs.append(-1)
iWs.append(N)

ans = 0
for i in range(min(len(iRs), len(iWs))):
    iW = iWs[i]
    iR = iRs[i]
    #
    if iW >= iR:
        break
    else:
        ans += 1

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
c = input()

cr = c.count('R')
cnt = 0
for i, ci in enumerate(c):
    if ci == 'R' and i >= cr:
        cnt += 1

print(min([cr, n-cr, cnt]))

Submission status: Accepted

Solution code:
n=int(input())
c=input()
print(c.count("W")-c[n-c.count("W"):].count("W"))

Submission status: Accepted

Solution code:
N = int(input())
c = list(input())
num_r = 0
for ci in c:
    if ci == 'R':
        num_r += 1
ans = 0
if num_r != N and num_r != 0:
    for i in range(num_r):
        if c[i] == 'W':
            ans += 1
print(ans)

Submission status: Accepted

Solution code:

import sys
sys.setrecursionlimit(10**7)

readline = sys.stdin.buffer.readline
def readstr():return readline().rstrip().decode()
def readstrs():return list(readline().decode().split())
def readint():return int(readline())
def readints():return list(map(int,readline().split()))
def printrows(x):print('\n'.join(map(str,x)))
def printline(x):print(' '.join(map(str,x)))

import math
n = readint()
c = readstr()

r = c.count('R')
w = c.count('W')
ans = 0
for i in range(r):
    if c[i]=='W':
        ans += 1
for i in range(r+1,n):
    if c[i]=='R':
        ans += 1
print(math.ceil(ans/2))

Submission status: Accepted

Solution code:
N=int(input())
S=input()
red=S.count('R')
count=0
for i in range(red):
  if S[i]=='W':
    count+=1
print(count)

Submission status: Accepted

Solution code:
n = int(input())
c = list(input())
schw = 0
schr = n-1
ans = 0
while schw < schr:
    while c[schw] != 'W' and schw < n-1:
        schw += 1
    while c[schr] != 'R' and schr > 0:
        schr -= 1
    ans += 1
    c[schw] = 'R'
    c[schr] = 'W'
print(ans - 1)

Submission status: Accepted

Solution code:
def next_white(s, w, n):
    w += 1
    while s[w] != 'W':
        w += 1
        if w > n - 1:
            return n
    return w


def next_red(s, r,n):
    r -= 1
    while s[r] != 'R':
        r -= 1
        if r < 0:
            return -1
    return r


n = int(input())
s = input()
white = -1
red = n
ans = -1
while red > white:
    ans += 1
    white = next_white(s, white, n)
    red = next_red(s, red, n)
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
c = input().strip()
r = c.count("R")
ans = 0
for i in range(r):
    if c[i] == "W":
        ans += 1
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
c=input()
cnt=c.count("R")
c_short=c[:cnt]
print(c_short.count("W"))

Submission status: Accepted

Solution code:

n=int(input())
c=input()
w=0
ch=[0 for _ in range(n)]

for i in range(n):
    if c[i]=="W":
        ch[i]=1
        w+=1
print(sum(ch[:n-w]))

Submission status: Accepted

Solution code:
n = int(input())
n += 4
s = str(input())
s = "WR" + s + "WR"
lis = []
num = 1
for i in range(n-1):
    if s[i] != s[i+1]:
        lis.append(num)
        num = 1
    else:
        num += 1
lis.append(num)
  #print(lis)
W = 2
R = len(lis)-3

ans = 0
while W < R:
    if lis[W] > 0 and lis[R] > 0:
        lis[R] -= 1
        lis[W] -= 1
        ans += 1
    else:
        if lis[W] == 0:
            W += 2
        if lis[R] == 0:
            R -= 2
print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**8)
def ii(): return int(sys.stdin.readline())
def mi(): return map(int, sys.stdin.readline().split())
def li(): return list(map(int, sys.stdin.readline().split()))
def li2(N): return [list(map(int, sys.stdin.readline().split())) for i in range(N)]
def dp2(ini, i, j): return [[ini]*i for i2 in range(j)]
#import bisect #bisect.bisect_left(B, a)
#from collections import defaultdict #d = defaultdict(int) d[key] += value
#from collections import Counter # a = Counter(A).most_common()
#from itertools import accumulate #list(accumulate(A))

N = ii()
S = input()

num_r = S.count('R')
ans = num_r

for i in range(num_r):
    if S[i] == 'R':
        ans -= 1

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
a = input()
al = len(a)

l = 0
r = al-1
cnt = 0
#print(a,al,l,r)
while True:
    if l >= r:
        break
    if a[l] == 'R':
        l += 1
        continue
    
    if a[r] == 'W':
        r += -1
        continue
    l += 1
    r += -1
    cnt += 1
    
print(cnt)

Submission status: Accepted

Solution code:
# import sys
# import math #sqrt,gcd,pi
# import decimal
# import queue # queue
# import bisect
# import heapq # priolity-queue
# import time
# from itertools import product,permutations,\
    # combinations,combinations_with_replacement
# 重複あり順列、順列、組み合わせ、重複あり組み合わせ
# import collections # deque
# from operator import itemgetter,mul
# from fractions import Fraction
# from functools import reduce

mod = int(1e9+7)
# mod = 998244353
INF = 1<<50

def readInt():
    return list(map(int,input().split()))

def Divisors(a): # 約数列挙
    divisors = []
    for i in range(1,int(a**0.5)+1):
        if a%i==0:
            divisors.append(i)
            if i!=a//i:
                divisors.append(a//i)
    divisors.sort()
    return divisors

def main():
    n = int(input())
    c = input()
    red = 0
    for i in range(n):
        if c[i]=='R':
            red += 1
    ans = 0
    for i in range(red):
        if c[i]=='W':
            ans += 1
    print(ans)
    return

if __name__=='__main__':
    main()

Submission status: Accepted

Solution code:
n=int(input())

c = list(input())
num_R=c.count("R")

num_left_R=c[:num_R].count("R")
#print(num_R)
#print(num_left_R)
print(num_R-num_left_R)

Submission status: Accepted

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


def solve(N, C):
    cnt = 0
    i = 0
    j = N - 1
    while i < N and j >= 0:
        while True:
            if C[i] == "W":
                break
            i += 1
            if i >= N:
                break
        while True:
            if C[j] == "R":
                break
            j -= 1
            if j < 0:
                break
        if i >= j:
            break
        else:
            cnt += 1
            i += 1
            j -= 1
    print(cnt)
    return


# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))
    S = next(tokens)
    C = [S[i] for i in range(N)]
    solve(N, C)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N = int(input())
C = list(input())
nR = C.count('R')
nW = N - nR

mR = 0
for c in C[:nR]:
    if c=='W': mR += 1

print(mR)

Submission status: Accepted

Solution code:
n=int(input())
s=input()
c=s.count("R")
print(s[:c].count("W"))

Submission status: Accepted

Solution code:
n = int(input())
C = list(str(input()))

W = []
R = []
for i in range(n):
    if C[i] == 'W':
        W.append(i)
    else:
        R.append(i)

W.reverse()
#print(W)
#print(R)
nR = []
nW = []
ans = 0
for i in range(len(R)):
    r = R.pop()
    if len(W) > 0:
        w = W.pop()
        if w < r:
            nR.append(w)
            nW.append(r)
            ans += 1
        else:
            R.append(r)
            W.append(w)
            nW += W
            nR += R
            break
    else:
        R.append(r)
        nW += W
        nR += R
        break
#print(ans)
nR.sort()
nW.sort()
if len(nR) == 0 or len(nW) == 0:
    print(ans)
    exit()
for idx in nW:
    if idx < nR[0]:
        ans += 1
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
C = list(input())

r_num = C.count('R')
ans = C[:r_num].count('W')
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
c = list(input())
color = [i == 'R' for i in c]
ans = 0
checked = 0
for right in range(N - 1, -1, -1):
    if color[right]:
        for left in range(checked, right):            
            if not color[left]:
                color[right], color[left] = color[left], color[right]
                ans += 1
                checked = left
                break
        checked = left
print(ans)

Submission status: Accepted

Solution code:
import queue

N=int(input())
A=queue.deque(list(input()))

ans=0
while A:
    if A.popleft()=='W':
        if not A:
            break
        else:
            while A:
                if A.pop()=='R':
                    ans+=1
                    break
            
print(ans)

Submission status: Accepted

Solution code:
import collections
N = int(input())
c = input()
A = collections.Counter(c)["R"]
B = collections.Counter(c[A:])["R"]
print(B)

Submission status: Accepted

Solution code:
import sys
from collections import deque
import numpy as np
import math
sys.setrecursionlimit(10**6)
def S(): return sys.stdin.readline().rstrip()
def SL(): return map(str,sys.stdin.readline().rstrip().split())
def I(): return int(sys.stdin.readline().rstrip())
def IL(): return map(int,sys.stdin.readline().rstrip().split())

if __name__=='__main__':
    n = I()
    c = list(S())
    i,j = 0,n-1
    ans = 0
    while i<j:
        while c[i]=='R':
            i += 1
            if i==n-1:
                break
        while c[j]=='W':
            j -= 1
            if j==0:
                break
        if i<j:
            c[i],c[j] = c[j],c[i]
            i += 1
            j -= 1
            ans += 1
    print(ans)
    exit()

Submission status: Accepted

Solution code:
N = int(input())
C = list(input())

def solve(N, C):
    R = 'R'
    W = 'W'
    if C.count('W') == 0:
        return 0
    if C.count('R') == 0:
        return 0

    w = 0
    r = len(C)-1
    count  = 0

    while w < r:
        while w < r and C[w] != W:
            w+=1
        while w < r and C[r] != R:
            r-=1
        if r <= w:
            return count
        else:
            #print(C, w, r)
            C[w], C[r] = 'R', 'W'
            count+= 1
    return min(count, C.count("R"))

print(solve(N, C))

Submission status: Accepted

Solution code:
n=int(input())
a=list(input())
r=a.count('R')

ans=0

for x in range(r):
  if a[x]=='R':
    ans+=1
    
print(r-ans)

Submission status: Accepted

Solution code:
def main():
    from sys import setrecursionlimit, stdin, stderr
    from os import environ
    from collections import defaultdict, deque, Counter
    from math import ceil, floor
    from itertools import accumulate, combinations, combinations_with_replacement
    setrecursionlimit(10**6)
    dbg = (lambda *something: stderr.write("\033[92m{}\033[0m".format(str(something)+'\n'))) if 'TERM_PROGRAM' in environ else lambda *x: 0
    input = lambda: stdin.readline().rstrip()
    LMIIS = lambda: list(map(int,input().split()))
    II = lambda: int(input())
    P = 10**9+7
    INF = 10**18+10

    N = II()
    C = list(input())
    l = 0
    r = N-1
    ans = 0
    while l < r:
        while C[l] != 'W' and l < N-1:
            l += 1
        while C[r] != 'R' and 0 < r:
            r -= 1
        if l < r:
            ans += 1
            l += 1
            r -= 1
        else:
            break
    print(ans)

    
main()

Submission status: Accepted

Solution code:
from math import floor,ceil,sqrt
import fractions
from collections import deque
import itertools
import collections
from heapq import *
#RRR...WWW...にしたい
N=int(input())
stones=list(input())
#print(stones)
l=0
r=N-1
wchange=0
rchange=0
cnt=0
while l<r:
    if (wchange==0)and(stones[l]=="W"):
        wchange=1
    elif (wchange==0)and(stones[l]=="R"):
        l=l+1

    if (rchange==0)and(stones[r]=="R"):
        rchange=1
    elif (rchange==0)and(stones[l]=="W"):
        r=r-1

    if wchange+rchange==2:
        buf=stones[l]
        stones[l]=stones[r]
        stones[r]=buf
        cnt=cnt+1
        wchange=0
        rchange=0
    #print(l,wchange,r,rchange,stones)
print(cnt)

Submission status: Accepted

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

def mp(): return map(int, input().split())
def lmp(): return list(map(int, input().split()))

n = int(input())
c = list(input())
r = 0
w = 0
for i in range(n):
    if c[i] == "R":
        r += 1
    else:
        w += 1
ans = 0
for i in range(r):
    if c[i] != "R":
        ans += 1
print(ans)

Submission status: Accepted

Solution code:
import os
import sys
from io import BytesIO, IOBase
# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# ------------------------------

def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
def toord(c): return ord(c)-ord('a')
def lcm(a, b): return a*b//lcm(a, b)
mod = 998244353
INF = float('inf')
from math import factorial, sqrt, ceil, floor, gcd
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush


# ------------------------------


def main():
    n = N()
    s = input()

    b, e = 0, n-1
    res = 0

    while b<e:
        while b < n and s[b] == 'R': b += 1
        while e > -1 and s[e] == 'W': e -= 1
        if b>=e: break
        res+=1
        b+=1
        e-=1
    print(res)


if __name__ == "__main__":
    main()