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():
    '''
    code here
    '''
    N = int(input())
    stones = input()

    w = []
    r = []

    for i in range(N):
        if stones[i] == 'W':
            w.append(i)
        else:
            r.append(i)

    if len(w) != 0 and len(r) != 0:
        res = 0
        for i, val in enumerate(w):
            if val <= r[-1*(i+1)]:
                res += 1
            else:
                break
        print(res)
    else:
        print(0)

if __name__ == "__main__":
    resolve()

Submission status: Accepted

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

n = int(input())
rw = input()

w = 0

c = [0] * n

for i in range(n):
    if rw[i] == 'W':
        c[i] = 1
        w += 1

r = n - w

left_w = 0
for x in c[0:r]:
    if x == 1:
        left_w += 1

print(left_w)

Submission status: Accepted

Solution code:
from collections import Counter

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

C = Counter(S)
ans = 0
for i in range(C['R']):
    if S[i] == 'W':
        ans += 1
print(ans)

Submission status: Accepted

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

ans = C.count("R")
ans = min(ans, N - ans)

from heapq import *

idxW = []
idxR = []
for i,c in enumerate(C):
    if c == "R":
        heappush(idxR, -i)
    else:
        heappush(idxW, i)

LEN = min(len(idxW), len(idxR))

cnt = 0
for i in range(LEN):
    iW = heappop(idxW)
    iR = heappop(idxR) * (-1)

    if iW < iR:
        cnt += 1

ans = min(ans, cnt)

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
c = input()
num = c.count("R")
c2 = c[:num]
num2 = c2.count("R")
print(num - num2)

Submission status: Accepted

Solution code:
n = int(input())
s = input()
ans = 0

while True:
    if not ('R' in s and 'W' in s): break
    r = s.rindex('R')
    w = s.index('W')
    if r < w:
        break
    s = s[:w] + 'R' + s[w+1:r] + 'W' + s[r+1:]
    ans += 1
print(ans)

Submission status: Accepted

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

r = []
w = []

for i in range(n):
    if c[i] == 'R':
        r.append(i)
    else:
        w.append(i)

r.sort(reverse=True)

if len(r) == 0 or len(w) == 0:
    print(0)
else:
    ans = 0
    while ans < len(r) and ans < len(w) and r[ans] > w[ans]:
        ans += 1
    print(ans)

Submission status: Accepted

Solution code:

def main():
    t = int(input())
    arr = list(input())

    count = 0
    left = 0
    right = t-1

    # W R W W R W R R

    while left < right:
        if arr[right] == 'R' and arr[left] == 'W':
            # arr[left], arr[right] = arr[right], arr[left]
            left += 1
            right -= 1
            count += 1

        elif arr[left] == 'R' and arr[right] =='R' :
            left += 1

        elif arr[left] == 'W' and arr[right] =='W':
            # left += 1
            right -= 1
            # count += 1

        else:
            left += 1
            right -= 1




    print(count)




main()

Submission status: Accepted

Solution code:
import heapq

N = int(input())
stones = input()

red = []
white = []
heapq.heapify(red)
heapq.heapify(white)

for i in range(N):
    if stones[i] == 'R':
        heapq.heappush(red, -i)
    else:
        heapq.heappush(white, i)

a = len(red)
b = N - a

if a == 0 or b == 0:
    print(0)
else:
    count = 0
    while True:
        biggest_red = -(heapq.heappop(red))
        smallest_white = heapq.heappop(white)
        if biggest_red > smallest_white:
            count += 1
            heapq.heappush(red, smallest_white * -1)
            heapq.heappush(white, biggest_red)
        else:
            break
    print(min(a, b, count))

Submission status: Accepted

Solution code:

N = int(input())
C = input()
w = C.count("W")
print(w - C[N-w::].count("W"))

Submission status: Accepted

Solution code:
n = int(input())
s = input()
w = []
r = []
for i in range(len(s)):
    if s[i] == "W": w.append(i+1)
    if s[len(s)-i-1] == "R": r.append(len(s)-i)
cnt = 0
# print(w,r)
for i in range(min(len(w), len(r))):
    if w[i] >  r[i]:
        break
    else:
        cnt += 1
print(cnt)

"""
i = 0
while True:
    wi = s.index("W")
    ri = str(s).rindex("R")
    if wi < ri:
        s[wi], s[ri] = s[ri], s[wi]
        i += 1
    else: break
print(cnt)
"""

Submission status: Accepted

Solution code:
n=int(input())
c=list(input())
ideal=["R"]*c.count("R")+["W"]*c.count("W")

cnt=0
for i in range(n):
    if c[i]!=ideal[i]:
        cnt+=1

print(min([c.count("R"), c.count("W"), (cnt+1)//2]))

Submission status: Accepted

Solution code:
import numpy as np

N=int(input())
c=np.array(list(input()))
n=np.count_nonzero(c == 'R')
i=0
j=N-1
cnt=0
if N==n:
    print(cnt)
    exit(0)
while 1:
    while c[i]!='W' and i<n:
        i+=1
    while c[j]!='R' and j>n-1:
        j-=1
    if i>=n or j<n:
        print(cnt)
        exit(0)
    temp=c[i]
    c[i]=c[j]
    c[j]=temp
    cnt+=1

print(cnt)

Submission status: Accepted

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

from collections import Counter
cl = list(c)
cun= Counter(cl)
cn=cun["R"]
cnt=0
for i in  range(cn):
    if c[i]=="W" :
        rpos=c.rfind("R",cn)
        cl[i],cl[rpos]=cl[rpos],cl[i]
        cnt+=1

print(cnt)

Submission status: Accepted

Solution code:
"""
RRR...RWWW...Wの並びに並び変えるのがゴール
"""

N = int(input())
c = input()

nw = 0
nr = 0

for i in c:
    if i == 'W':
        nw += 1
    elif i == 'R':
        nr += 1

lw = 0
rr = 0

for i in range(0, nr):
    if c[i] == 'W':
        lw += 1

for i in range(nr, len(c)):
    if c[i] == 'R':
        rr += 1

print(max(lw, rr))

Submission status: Accepted

Solution code:
#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase


def main():
    n = int(input())
    s = list(input())
    w_cnt = s.count('W')
    r_cnt = n - w_cnt
    ideal = list('R' * r_cnt + 'W' * w_cnt)
    exchange = 0
    replace = 0
    flag = 0
    for i in range(n-1, -1, -1):
        if s[i] == 'R' and not flag:
            flag = 1
        if flag and s[i] == 'W':
            replace += 1
        if s[i] != ideal[i] and s[i] == 'W':
            exchange += 1
    print(min(replace, exchange))



# 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")

# endregion

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N=int(input())
C=input()
NR=0
NW=0
ans=0
for i in range(N):
  if C[i]=="W":
    NW+=1
  else:
    NR+=1
if NW==N or NR==N:
  print(0)
else:
  for i in range(NR):
    if C[i]=="W":
      ans+=1
  print(ans)

Submission status: Accepted

Solution code:

N = int(input())
line = list(input())
rw = {"R": [], "W": []}
ans = N


def replace(c):
    left = -1
    right = len(rw["R"])
    while right - left > 1:
        idx = (right + left) // 2
        if rw["R"][idx] > c:
            right = idx
        else:
            left = idx
    req = len(rw["R"]) - right
    return req


for cnt, i in enumerate(line):
    if i == "R":
        if len(rw["R"]) == 0:
            rw["R"] = [cnt]
        else:
            rw["R"].append(cnt)
    else:
        if len(rw["W"]) == 0:
            rw["W"] = [cnt]
        else:
            rw["W"].append(cnt)
ans = min(len(rw["R"]), len(rw["W"]))
ans = min(ans, replace(len(rw["R"])-1))
print(ans)

Submission status: Accepted

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


ans = 0
left_W = 0
right_R =c.count("R")

if c.count("R")==0 or c.count("W") == 0:
    ans = 0
for n in range (N):
    if c[n] == "R":
        right_R -= 1
    else:
        left_W += 1


    if left_W == right_R:
        ans = right_R
        break
print(ans)

Submission status: Accepted

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

if N <= 1:
    print(0)
else:
    ans = 0
    r = N
    for w in range(N):
        if c[w] == 'R':
            continue
        else:
            while True:
                r += -1
                if r == -1 or c[r] == 'R':
                    break
            if r < w:
                break
            else:
                ans += 1
    print(ans)

Submission status: Accepted

Solution code:
# coding: utf-8


def solve(*args: str) -> str:
    n = int(args[0])
    RED = [a == 'R' for a in args[1]]
    l, r = 0, n-1
    ret = 0
    while l < r:
        if RED[l]:  # left:red
            l += 1
        elif RED[r]:  # left:white & right:red
            l += 1
            r -= 1
            ret += 1
        elif not RED[r]:  # left: white & right: white
            r -= 1

    return str(ret)


if __name__ == "__main__":
    print(solve(*(open(0).read().splitlines())))

Submission status: Accepted

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

redflag = False
whiteflag = False
# for i in range(n):
#   if(stones[i]=="R"):
#     redflag = true
#   else:
#     whiteflag = true

# if(not(redflag and whiteflag)):
#   print(0)

start = 0
end = n - 1
count = 0
while(True):
  while(start < n and stones[start]!="W"):
    start += 1
  while(end >= 0 and stones[end]!="R"):
    end -= 1
  if(start >= end):
    break
  start += 1
  end -= 1
  count += 1

print(count)

Submission status: Accepted

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

RightW=0
tesu=0

LeftW=0
LeftR=0

numW=0
numR=0

for i in RW:
  if i=="R":
    numR+=1
  else:
    numW+=1

for i in range(numR):
  if RW[i]=="W":
    LeftW+=1
  else:
    LeftR+=1

print(LeftW)

Submission status: Accepted

Solution code:
import collections

c=input()
c=input()

tmp=collections.Counter(c)

count_r=0
count_w=0
ans=0
dis_r=0

for i in c:
    if dis_r == tmp["R"]:
        break
        
    elif i == "W":
        if count_r<=tmp["R"]:
            ans+=1
            dis_r+=1
        else:
            ans+=1
    else:
        count_r+=1
        dis_r+=1
print(ans)

Submission status: Accepted

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

R = c.count("R")

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

print(cnt)

Submission status: Accepted

Solution code:
import math
N=int(input())
S=list(input())
ans=0
Rc=S.count('R')
Wc=N-Rc
Wco=S[:Rc].count('W')
Rco=Rc-Wco
Wcu=Wc-Wco
Rcu=Rc-Rco

#print(Rco)
#print(Wco)
#print(Rcu)
#print(Wcu)


print(min(Rc,Wc,max(Wco,Rcu)))

Submission status: Accepted

Solution code:
from collections import Counter
n=int(input())
c=input()
co=Counter(c)
wcnt=co["W"]
rcnt=co["R"]
if wcnt==0 or rcnt==0:
    print(0)
    quit()
ans=0
for i in range(n):
    if c[i]=="W" and i<rcnt:
        ans+=1

print(min(ans,rcnt))

Submission status: Accepted

Solution code:
import sys

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

N = int(readline())
C = read().rstrip().decode()

l, r = 0, N - 1
cost = 0
while l < r:
    # [l,r] がまだ
    if C[l] == 'R':
        l += 1
    elif C[r] == 'W':
        r -= 1
    else:
        # R...W
        cost += 1
        l += 1
        r -= 1

print(cost)

Submission status: Accepted

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

array = list(s)
r = len(s.replace('W', ''))
w = n - r
ans = min(r,w)

i = 0
j = len(array)-1
count = 0
for i in range(r):
  if array[i] == 'W':
    count += 1
  
print(min(count, ans))

Submission status: Accepted

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

m = s.count("R")
ans = s[:m].count("W")

print(ans)

Submission status: Accepted

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

print(C.count("R") - C.count("R", 0, C.count("R")))

Submission status: Accepted

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

r = c.count("R")

if r == 0 or r == len(c):
    print("0")
    exit()

print(c[:r].count("W"))

Submission status: Accepted

Solution code:
n = int(input())

s = list(input())

w = s.count("R")
#print(w)
x = s[:w].count("R")
#print(x)

print(w-x)

Submission status: Accepted

Solution code:
n = int(input())
k = input()
k2 = k[::-1]
i1 = 0
i2 = 0
cnt = 0
while i1 < n:
  if k[i1] == 'W':
    while i2 < n:
      if k2[i2] == 'R':
        i2 += 1
        cnt += 1
        break
      i2 += 1
      if i1 + i2 >= n:
        break
  i1 += 1
  if i1 + i2 >= n:
    break
print(cnt)

Submission status: Accepted

Solution code:
N=int(input())
c=input()
dataR=[int(c[i]=="R") for i in range(N)]
dataW=[int(c[i]=="W") for i in range(N)]

for i in range(N-2,-1,-1):
    dataR[i]+=dataR[i+1]
for i in range(1,N):
    dataW[i]+=dataW[i-1]

ans=min(dataR[0],dataW[N-1])
for i in range(1,N):
    test=max(dataR[i],dataW[i-1])
    ans=min(ans,test)

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
s = str(input())
cnt1 = s.count("W") # Wの文字数
cnt2 = len(s) - cnt1 # Rの文字数
ss = s[:cnt2]
cnt3 = ss.count("W")
print(min(cnt1, cnt3))

Submission status: Accepted

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

r = C.count("R")
print(r-C[:r].count("R"))

Submission status: Accepted

Solution code:
n = int(input())
s = input()
n_r = s.count('R')
n_r_l = s[:n_r].count('R')
print(n_r-n_r_l)

Submission status: Accepted

Solution code:
from collections import Counter
N = int(input())
c = input()
counter = Counter(c)

if counter["R"] == 0 or counter["W"] == 0:
    print(0)
else:
    r_cnt = 0
    for i in range(counter["R"]):
        if c[i] == "R":
            r_cnt += 1
    print(counter["R"]-r_cnt)

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.buffer.readline
def even(n): return 1 if n%2==0 else 0

n = int(readline())

s = readline().rstrip().decode('utf-8')

l = 0
r = n-1
ans = 0
while l < r:
    if s[l] == "W" and s[r] == "R":
        ans += 1
        l += 1
        r -= 1
    if s[l] == "R":
        l += 1
    if s[r] == "W":
        r -= 1

print(ans)

Submission status: Accepted

Solution code:
import sys
import heapq
import math
import fractions
import bisect
import itertools
from collections import Counter
from collections import deque
from operator import itemgetter
def input(): return sys.stdin.readline().strip()
def mp(): return map(int,input().split())
def lmp(): return list(map(int,input().split()))

n=int(input())
s=input()
c=s.count("R")
w=[0]*n
if c==0 or c==n:
    print(0)
    exit()
if s[0]=="W":
    w[0]=1
for i in range(1,n):
    w[i]=w[i-1]
    if s[i]=="W":
        w[i]+=1
print(w[c-1])

Submission status: Accepted

Solution code:
import sys
import itertools
# import numpy as np
import time
import math
import heapq
from collections import defaultdict
sys.setrecursionlimit(10 ** 7)
 
INF = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

# map(int, input().split())

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

goal = sorted(S)

ans = 0
for i in range(N):
    if S[i] != goal[i]:
        ans += 1
print(ans // 2)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**9)

def mi(): return map(int,input().split())
def ii(): return int(input())
def isp(): return input().split()
def deb(text): print("-------\n{}\n-------".format(text))

INF=10**20
def main():
    N=ii()
    C = list(input())

    R = []
    W = []
    for i,c in enumerate(C):
        if c == "R":
            R.append(i)
        else:
            W.append(i)
    

    W.sort(reverse=True)
    R.sort()

    if len(R) == 0 or len(W) == 0:
        print(0)
        exit()

    ri = R.pop()
    wi = W.pop()

    ans = 0
    while not ri < wi:
        ans += 1
        if len(R) == 0 or len(W) == 0: break

        ri = R.pop()
        wi = W.pop()    


    print(ans)






if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
def main():
    n = int(input())
    s = input()

    wcount = s.count("W")
    rcount = s.count("R")

    ans = 0

    for i in range(rcount):
        if s[i] == "W":
            ans+=1
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys, re
def i_input(): return int(input())
def s_input(): return input()
sys.setrecursionlimit(10 ** 6)

def main():
    n = i_input()
    s = list(s_input())

    r_count = s.count('R')
    w_count = n - r_count

    if r_count == n or w_count == n:
        print(0)
        exit()

    r_s = s[::-1]

    count = 0

    index = 0
    for i in range(len(s)):
        if r_s[i] == 'W':
            continue
        for j in range(index, n - i - 1):
            if s[j] == 'R':
                index = j + 1
                continue
            index = j + 1
            count += 1
            break

    print(min(count, min(r_count, w_count)))

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import bisect, collections, copy, heapq, itertools, math, string, sys
input = lambda: sys.stdin.readline().rstrip() 
sys.setrecursionlimit(10**7)
INF = float('inf')
def I(): return int(input())
def F(): return float(input())
def SS(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LSS(): return input().split()

def resolve():
    N = I()
    c = list(SS())

    # R...RW...Wにしたい
    # WRWWRWRR
    # RRWWRWRW
    # RRRWRWWW
    # RRRRWWWW
    cnt_r = c.count('R')
    ans = max(c[:cnt_r].count('W'), c[cnt_r:].count('R'))
    # print(c[:cnt_r], c[cnt_r:])
    print(ans)

if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
n = int(input())
s = list(input())
num_R = 0
for i in range(n):
    if s[i]=='R':
        num_R+=1
s_sort = ['R' if i<num_R else 'W' for i in range(n)]
ans = 0
for i in range(n):
    if s[i]=='W' and s_sort[i]=='R':
        ans += 1
    
print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect_left, bisect_right

class Result:
    def __init__(self, index, value):
        self.index = index
        self.value = value

class BinarySearch:
    def __init__(self):
        pass

    @staticmethod
    def greater_than(num: int, func, size: int = 1):
        """Searches for smallest element greater than num!"""
        if isinstance(func, list):
            index = bisect_right(func, num)
            if index == len(func):
                return Result(None, None)
            else:
                return Result(index, func[index])
        else:
            alpha, omega = 0, size - 1
            if func(omega) <= num:
                return Result(None, None)
            while alpha < omega:
                if func(alpha) > num:
                    return Result(alpha, func(alpha))
                if omega == alpha + 1:
                    return Result(omega, func(omega))
                mid = (alpha + omega) // 2
                if func(mid) > num:
                    omega = mid
                else:
                    alpha = mid

    @staticmethod
    def less_than(num: int, func, size: int = 1):
        """Searches for largest element less than num!"""
        if isinstance(func, list):
            index = bisect_left(func, num) - 1
            if index == -1:
                return Result(None, None)
            else:
                return Result(index, func[index])
        else:
            alpha, omega = 0, size - 1
            if func(alpha) >= num:
                return Result(None, None)
            while alpha < omega:
                if func(omega) < num:
                    return Result(omega, func(omega))
                if omega == alpha + 1:
                    return Result(alpha, func(alpha))
                mid = (alpha + omega) // 2
                if func(mid) < num:
                    alpha = mid
                else:
                    omega = mid

# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase

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")

# ------------------- fast io --------------------
from math import gcd, ceil

def pre(s):
    n = len(s)
    pi = [0] * n
    for i in range(1, n):
        j = pi[i - 1]
        while j and s[i] != s[j]:
            j = pi[j - 1]
        if s[i] == s[j]:
            j += 1
        pi[i] = j
    return pi


def prod(a):
    ans = 1
    for each in a:
        ans = (ans * each)
    return ans

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


def binary(x, length=16):
    y = bin(x)[2:]
    return y if len(y) >= length else "0" * (length - len(y)) + y


for _ in range(int(input()) if not True else 1):
    n = int(input())
    s = input()
    r = []
    w = []
    for i in range(n):
        if s[i] == 'R':
            r += [i]
        else:
            w += [i]
    bs = BinarySearch()
    ans = 0
    for i in range(n):
        if s[i] == 'W':
            if bs.greater_than(i, r).value is not None:
                r.pop()
                ans += 1
    print(ans)

Submission status: Accepted

Solution code:
n=int(input())
c=input()
r=c.count("R")
w=n-r
ans=0
for i,j in zip(c,"R"*r+"W"*w):
    if i!=j:
        ans+=1
print(ans//2)

Submission status: Accepted

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

lista=list(a)
w=lista.count("W")
r=lista.count("R")
count=0
for i in range(r):
  if lista[i]=="W":
    count+=1
print(count)

Submission status: Accepted

Solution code:
n = int(input())
c = input()
r_cnt = c.count('R')
w_cnt = c.count('W')
new_c = 'R' * r_cnt + 'W' * w_cnt
cnt = 0
for i in range(n):
    if c[i] != new_c[i]:
        cnt += 1
    else:
        pass
if cnt >= 2:
    ans = cnt //2
elif cnt == 1:
    ans = 1
elif cnt == 0:
    ans = 0
print(ans)

Submission status: Accepted

Solution code:
a=int(input())
b=input()
r_num=0
w_num=0
for i in b :

  if i=='W' :
    w_num+=1
  else :
    r_num+=1

count=0

for i in range(r_num) :
  if b[i]=='W' :
    count+=1


print(count)

Submission status: Accepted

Solution code:
n = int(input())
c = list(input())
wc = 0

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

rc = n - wc

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

rinwcount = 0
for i in range(rc, n, 1):
    if c[i] == "R":
        rinwcount += 1

if winrcount >= rinwcount:
    print(winrcount)
else:
    print(rinwcount)

Submission status: Accepted

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

siro = s.count('W')
aka = n - siro
ans = 0
for i in range(aka, n):
    if s[i] == 'R':
        ans += 1
print(ans)

Submission status: Accepted

Solution code:
n = 0
c = []
ans = 0
"""
def changePosition(int stone1,int stone2):
    r = c[stone1]
    c[stone1] = c[stone2]
    c[stone2] = r
    ans += 1

def changeColor(int stone):
    if c[stone]=="R":
        c[stone]="W"
    else:
        c[stone]="R"
    ans += 1
"""

def main():
    n = int(input())
    c = input()

    red=c.count("R")
    num=c[0:red].count("R")
    print(red-num)


main()

Submission status: Accepted

Solution code:
n = int(input())
s = str(input())

nw = s.count("W")
nr = s.count("R")

change = s[nr:].count("R")

print(min(nw, nr, change))

Submission status: Accepted

Solution code:
n = int(input())
c = [i for i in input()]
cnt = 0
for num, i in enumerate(sorted(c)):
    if c[num] != i:
        cnt += 1
print(cnt // 2)

Submission status: Accepted

Solution code:
N = int(input())
# N = 4
stones = list(input())
# stones = ['W','R','R','R']
if not ('R' in stones and 'W' in stones):
    print('0')
    exit()
right = 0
left = N - 1
white_idx = -1
red_idx = -1
ans = 0
while right < left:
    while right < N and right < left:
        if stones[right] == 'W':
            white_idx = right
            break
        right += 1
    while 0 < left and right < left:
        if stones[left] == 'R':
            red_idx = left
            break
        left -= 1
    if left == right:
        break
    if 0 <= white_idx and 0 <= red_idx:
        ans += 1
    right += 1
    left -= 1
print(ans)

Submission status: Accepted

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

W_sum = stones.count('W')
R_sum = stones.count('R')

ans = min(W_sum, R_sum)
Wnum = 0
Rnum = 0
for i in range(n):
    if stones[i] == 'W':
        Wnum += 1
    else:
        Rnum += 1
    ans = min(ans, max(Wnum, R_sum - Rnum))

print(ans)

Submission status: Accepted

Solution code:
n=int(input())
arr=list(input())
w=arr.count('W')
r=arr.count('R')
ans=min(w,r)
leftr=r-arr[:r].count('R')
ans=min(ans,leftr)
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
s=input()
i,j=0,len(s)-1
while(i<len(s) and s[i]=='R'):
    i+=1
while(j>=0 and s[j]=='W'):
    j-=1
c=0
while i<j:
    
    if s[i]=='W' and s[j]=='R':
        c+=1
        i+=1
        j-=1
        while i<len(s) and s[i]=='R':
            i+=1
        while(j>=0 and s[j]=='W'):
            j-=1
    
print(c)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n=int(input())
ls=list(input())
r_ls = [i for i,v in enumerate(ls) if v=='R']
w_ls = [i for i,v in enumerate(ls) if v=='W']
end_flag = False
if len(r_ls) == 0 or len(w_ls) == 0:
    end_flag = True
else:
    r_mx, w_min = max(r_ls), min(w_ls)
    max_try = min(len(r_ls), len(w_ls))

r_i, w_i = -1, 0

if end_flag:
    print(0)
elif r_mx < w_min:
    print(0)
else:
    c = 0
    for i in range(max_try):
        c += 1
        r_ls[r_i], w_ls[w_i] =  w_ls[w_i], r_ls[r_i]
        if i == max_try -1:
            print(c)
            break
        else:
            try:
                r_mx = max(r_ls[r_i], r_ls[r_i - 1])
                w_min = min(w_ls[w_i], w_ls[w_i + 1])
            except:
                print(c)
                break
            if w_min > r_mx:
                print(c)
                break
            r_i -= 1
            w_i += 1

Submission status: Accepted

Solution code:
n=int(input())
c=list(input())
r=c.count('R')
#print(c)
cc=c[0:r]
ans=cc.count('W')
#print(cc)
print(ans)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sun Aug  2 21:11:34 2020

@author: NEC-PCuser
"""

N = int(input())

s = input()

l = 0
r = len(s) - 1
count = 0
while True:
	flg = False
	for i in range(l, r):
		if (s[i] == 'W'):
			l = i + 1
			flg = True
			break
	for j in range(r, l - 1, -1):
		if (s[j] == 'R'):
			r = j - 1
			if flg:
				count += 1
			break
	else:
		break
	if flg == False:
		break
print(count)

Submission status: Accepted

Solution code:

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

reds = 0
for c in s:
    reds += 1 if c == "R" else 0

whites = 0
for i in range(reds):
    whites += 1 if s[i] == "W" else 0

print(whites)

Submission status: Accepted

Solution code:
if __name__ == '__main__':
    n = int(input())
    c = input()

    r_count = c.count("R")
    w_count = c.count("W")

    diff = r_count - c[:r_count].count("R")
    print(diff)

Submission status: Accepted

Solution code:
from collections import deque

mod = 10**9+7
def I(): return int(input())
def LI(): return list(map(int,input().split()))
def MI(): return map(int,input().split())
def LLI(n): return [list(map(int, input().split())) for _ in range(n)]

N = I()
c = input()
r_num = c.count("R")

count = 0
for i in range(r_num):
  if(c[i] == "W"):
    count += 1
print(count)