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:
import heapq

N = int(input())
C = input()

W, R = [], []
heapq.heapify(W)
heapq.heapify(R)

ans = 0
for i in range(N):
    if C[i] == "W": heapq.heappush(W,i+1)
    if C[i] == "R": heapq.heappush(R,-(i+1))

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

ans = 0
while W[0] < -R[0]:
    w, r = heapq.heappop(W), -heapq.heappop(R)
    heapq.heappush(W,r)
    heapq.heappush(R,-w)
    ans += 1

print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
def resolve():
    N = int(input())
    C = list(input())
    idx_a, idx_d = 0, N - 1
    cnt = 0
    while idx_a < idx_d:
        if C[idx_a] != "W":
            idx_a += 1
            continue
        if C[idx_d] != "R":
            idx_d -= 1
            continue
        cnt += 1
        idx_a += 1
        idx_d -= 1
    print(cnt)

resolve()

Submission status: Accepted

Solution code:
'''     ░░█ ▄▀█ █   █▀ █░█ █▀█ █▀▀ █▀▀   █▀█ ▄▀█ █▀▄▀█  
        █▄█ █▀█ █   ▄█ █▀█ █▀▄ ██▄ ██▄   █▀▄ █▀█ █░▀░█     '''


# [temp1.py] => [29-07-2020 @ 10:25:10] 
# Author & Template by : Udit "luctivud" Gupta
# https://www.linkedin.com/in/udit-gupta-1b7863135/


import math;   from collections import *
import sys;    from functools import reduce
import time;   from itertools import groupby

# sys.setrecursionlimit(10**6)

def input()         : return sys.stdin.readline()
def get_ints()      : return map(int, input().strip().split())
def get_list()      : return list(get_ints())
def get_string()    : return list(input().strip().split())
def printxsp(*args) : return print(*args, end="")
def printsp(*args)  : return print(*args, end=" ")


DIRECTIONS = [(+0, +1), (+0, -1), (+1, +0), (+1, -1)] 
NEIGHBOURS = [(-1, -1), (-1, +0), (-1, +1), (+0, -1),\
              (+1, +1), (+1, +0), (+1, -1), (+0, +1)]


CAPS_ALPHABETS = {chr(i+ord('A')) : i for i in range(26)}
SMOL_ALPHABETS = {chr(i+ord('a')) : i for i in range(26)}
INF = float('inf')


# Custom input output is now piped through terminal commands.
# for _test_ in range(int(input())): 
n = int(input())
s = input()
c = s.count('R')
print(s[c:].count('R'))


# print("Time Elapsed: {}".format(float(S34p-S34t)))

Submission status: Accepted

Solution code:
"""
    Satwik_Tiwari ;) .
    2ND AUGUST , 2020  - SUNDAY
"""

#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function

from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase

from itertools import *
import bisect
from heapq import *
from math import *
from copy import *
from collections import deque
from collections import Counter as counter  # Counter(list)  return a dict with {key: count}
from itertools import combinations as comb # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
from itertools import permutations as permutate
from bisect import bisect_left as bl
#If the element is already present in the list,
# the left most position where element has to be inserted is returned.
from bisect import bisect_right as br
from bisect import bisect
#If the element is already present in the list,
# the right most position where element has to be inserted is returned

#==============================================================================================
#fast I/O region
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")


def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()


if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

# inp = lambda: sys.stdin.readline().rstrip("\r\n")

#===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
  def wrapped_func(*args, **kwargs):
    if stack: return f(*args, **kwargs)
    to = f(*args, **kwargs)
    while True:
      if type(to) is GeneratorType:
        stack.append(to)
        to = next(to)
        continue
      stack.pop()
      if not stack: break
      to = stack[-1].send(to)
    return to
  return wrapped_func
#### END ITERATE RECURSION ####

#===============================================================================================
#some shortcuts

mod = 1000000007
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var))  #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
# def graph(vertex): return [[] for i in range(0,vertex+1)]
def zerolist(n): return [0]*n
def nextline(): out("\n")  #as stdout.write always print sring.
def testcase(t):
    for p in range(t):
        solve()
def printlist(a) :
    for p in range(0,len(a)):
        out(str(a[p]) + ' ')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(a,b):
    ans = 1
    while(b>0):
        if(b%2==1):
            ans*=a
        a*=a
        b//=2
    return ans
def ncr(n,r): return factorial(n)//(factorial(r)*factorial(max(n-r,1)))
def isPrime(n) :
    if (n <= 1) : return False
    if (n <= 3) : return True
    if (n % 2 == 0 or n % 3 == 0) : return False
    i = 5
    while(i * i <= n) :
        if (n % i == 0 or n % (i + 2) == 0) :
            return False
        i = i + 6
    return True

#===============================================================================================
# code here ;))
def dist(a,b):
    return (((a**2)+(b**2))**0.5)

def solve():
    n = int(inp())
    s = list(inp())
    a = s.count('W')
    b = s.count('R')
    ans = 'R'*b + 'W'*a
    temp = 10**9
    cnt = 0
    for i in range(b):
        if(s[i] == 'W'):
            cnt+=1

    cnt1  = 0
    for i in range(b,n):
        if(s[i] == 'R'):
            cnt1+=1

    x,y = max(cnt,cnt1),min(cnt,cnt1)
    print(y+(x-y))


    # for i in range(n):


testcase(1)
# testcase(int(inp()))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
input = sys.stdin.readline
from collections import deque

n = int(input())
c = input().rstrip()
bad_white = deque()
bad_red = deque()
for i, ch in enumerate(c):
    if ch == "W":
        bad_white.append(i)
    else:
        bad_red.appendleft(i)

ans = 0
while bad_white and bad_red and bad_white[0] < bad_red[0]:
    bad_white.popleft()
    bad_red.popleft()
    ans += 1
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
c = input()
#優先度高 入れ替え
#優先度低 色かえ
red = c.count("R")
targ = c[0:red].count("R")
print(red-targ)

Submission status: Accepted

Solution code:
n = int(input())
S = input()
cnt = 0
i,j = 0,n-1
while i<j:
    if S[i]=='R' and S[j]=='R':
        i+=1
    elif S[i]=='R' and S[j]=='W':
        i += 1
        j -=1
    elif S[i]=='W' and S[j]=='W':
        j-=1
    else:
        cnt += 1
        i+=1
        j-=1
print(cnt)

Submission status: Accepted

Solution code:
import sys
input=lambda: sys.stdin.readline().rstrip()
n=int(input())
C=input()
L=[0]*(n+1)
R=[0]*(n+1)
for i in range(n):
  if C[i]=="W":
    L[i+1]=L[i]+1
  else:
    L[i+1]=L[i]
  if C[n-1-i]=="R":
    R[n-i-1]=R[n-i]+1
  else:
    R[n-i-1]=R[n-i]
ans=n
for i in range(n+1):
  cur=max(L[i],R[i])
  ans=min(ans,cur)
print(ans)

Submission status: Accepted

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

m = s.count('R')

print(s[:m].count('W'))

Submission status: Accepted

Solution code:
n = int(input())
c  = str(input())
x = 0
for i in range(n):
  if c[i] == "R":
    x += 1
a = 0
for i in range(x):
  if c[i] == "W":
    a += 1
print(a)

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, gcd
from itertools import accumulate, permutations, combinations, product, groupby, combinations_with_replacement
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N = INT()
c = input()
cnt = Counter(c)
t = "R"*cnt["R"]+"W"*cnt["W"]

ans = 0
for x, y in zip(c, t):
    ans += (x != y)
print(0--ans//2)

Submission status: Accepted

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

g=[0 for i in range(n)]
f=0

for i in range(n):
  if line[i]=="R":
    f=f+1
  g[i]=f

ans=f-g[f-1]
print(ans)

Submission status: Accepted

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

r=c.count("R")
ans=0

for i in range(N):
    if i<r and c[i]=="W":
        ans+=1
print(ans)

Submission status: Accepted

Solution code:
import heapq
N = int(input())
S = input()

ans = 0
w = []
r = []
for i, s in enumerate(S):
    if s == "W":
        w.append(i)
    else:
        r.append(-i)

if w and r:
    heapq.heapify(w)
    heapq.heapify(r)
    while w[0] < -r[0]:
        wi = heapq.heappop(w)
        ri = -heapq.heappop(r)
        heapq.heappush(w, ri)
        heapq.heappush(r, -wi)
        ans += 1

print(ans)

Submission status: Accepted

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
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
from operator import mul
from functools import reduce


sys.setrecursionlimit(2147483647)
INF = 10 ** 13
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().rstrip().split()
def S(): return sys.stdin.readline().rstrip()
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
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 = 998244353


n = I()
s = S()
now = 0
ans = 0
for i in range(n - 1, -1, -1):
    if now >= i:
        print(ans)
        exit()
    if s[i] == "R":
        while s[now] != "W":
            now += 1
            if now >= i:
                print(ans)
                exit()
        now += 1
        ans += 1

Submission status: Accepted

Solution code:
"""
                            pppppppppppppppppppp
                         ppppp  ppppppppppppppppppp
                      ppppppp    ppppppppppppppppppppp
                      pppppppp  pppppppppppppppppppppp
                      pppppppppppppppppppppppppppppppp
                              pppppppppppppppppppppppp
       ppppppppppppppppppppppppppppppppppppppppppppppp  pppppppppppppppppppp
      pppppppppppppppppppppppppppppppppppppppppppppppp  ppppppppppppppppppppp
     ppppppppppppppppppppppppppppppppppppppppppppppppp  pppppppppppppppppppppp
    ppppppppppppppppppppppppppppppppppppppppppppppp    pppppppppppppppppppppppp
   pppppppppppppppppppppppppppppppppppppppppppppp     pppppppppppppppppppppppppp
  ppppppppppppppppppppppppppppppppppppppppppppp      pppppppppppppppppppppppppppp
  pppppppppppppppppppppppppppppppp               pppppppppppppppppppppppppppppppp
  pppppppppppppppppppppppppppp     pppppppppppppppppppppppppppppppppppppppppppppp
  ppppppppppppppppppppppppppp    pppppppppppppppppppppppppppppppppppppppppppppppp
    pppppppppppppppppppppppp  pppppppppppppppppppppppppppppppppppppppppppppppppp
     ppppppppppppppppppppppp  ppppppppppppppppppppppppppppppppppppppppppppppppp
      pppppppppppppppppppppp  ppppppppppppppppppppppppppppppppppppppppppppppp
       ppppppppppppppppppppp  ppppppppppppppppppppppppppppppppppppppppppppp
                              pppppppppppppppppppppppp
                              pppppppppppppppppppppppppppppppp
                              pppppppppppppppppppppp  pppppppp
                              ppppppppppppppppppppp    ppppppp
                                 ppppppppppppppppppp  ppppp
                                    pppppppppppppppppppp
"""


import sys
from functools import lru_cache, cmp_to_key
from collections import defaultdict as dd, deque, Counter as C
from bisect import bisect_left as bl, bisect_right as br, bisect
from math import sqrt
mod = pow(10, 9) + 7
mod2 = 998244353
def data(): return sys.stdin.readline().strip()
def out(var, end="\n"): sys.stdout.write(str(var)+end)
def outa(*var, end="\n"): sys.stdout.write(' '.join(map(str, var)) + end)
def L(): return list(sp())
def sl(): return list(ssp())
def sp(): return map(int, data().split())
def ssp(): return map(str, data().split())
def l1d(n, val=0): return [val for i in range(n)]
def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)]


n = int(data())
s = list(data())
r = s.count('R')
cnt = 0
for i in range(r):
    if s[i] != 'R':
        cnt += 1
out(cnt)

Submission status: Accepted

Solution code:
import sys
import collections

sys.setrecursionlimit(10 ** 8)

input = sys.stdin.readline


def main():
    N = int(input())
    C = input().strip()

    cnt = collections.Counter(C)

    ans = min(cnt["W"], cnt["R"])

    if N <= 2:
        print(ans)
        return

    tmp = 0
    for i in range(N):
        if cnt["R"] == 0:
            break
        if C[i] == "W":
            cnt["R"] -= 1
            tmp += 1
        else:
            cnt["R"] -= 1

    ans = min(ans, tmp)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N = int(input())

C = input()

n = C.count('R')

print(n-C[:n].count('R'))

Submission status: Accepted

Solution code:
def main():
    N = int(input())
    c = input()
    ans = c.count('W')
    if ans == 0 or ans == N:
        print(0)
        exit()
    
    Ws = []
    Rs = []
    for i in range(N):
        if c[i] == 'W':
            Ws.append(i)
        if c[N-1-i] == 'R':
            Rs.append(N-1-i)

    Ws.append(N+1)
    Rs.append(-1)
    tmp = 0
    while Ws[tmp] < Rs[tmp]:
        tmp += 1
    
    print(min(ans,tmp))

if __name__ == "__main__":
    main()

Submission status: Accepted

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

r = 0
for c in C:
    if c == 'R':
        r += 1

ans = 0
for c in C[:r]:
    if c == 'W':
        ans += 1

print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**6)
INF = 10 ** 9 + 1  # sys.maxsize # float("inf")
MOD = 10 ** 9 + 7


def debug(*x):
    print(*x, file=sys.stderr)


def solve(N, CS):
    left = 0
    right = N - 1
    R = ord("R")
    W = ord("W")
    ret = 0
    while left < right:
        if CS[left] == R:
            left += 1
            continue
        if CS[right] == W:
            right -= 1
            continue
        # swap
        left += 1
        right -= 1
        ret += 1
    return ret


def main():
    # parse input
    N = int(input())
    CS = input().strip()
    print(solve(N, CS))


# tests
T1 = """
4
WWRR
"""
TEST_T1 = """
>>> as_input(T1)
>>> main()
2
"""

T2 = """
2
RR
"""
TEST_T2 = """
>>> as_input(T2)
>>> main()
0
"""

T3 = """
8
WRWWRWRR
"""
TEST_T3 = """
>>> as_input(T3)
>>> main()
3
"""


def _test():
    import doctest
    doctest.testmod()
    g = globals()
    for k in sorted(g):
        if k.startswith("TEST_"):
            doctest.run_docstring_examples(g[k], g)


def as_input(s):
    "use in test, use given string as input file"
    import io
    f = io.StringIO(s.strip())
    g = globals()
    g["input"] = lambda: bytes(f.readline(), "ascii")
    g["read"] = lambda: bytes(f.read(), "ascii")


input = sys.stdin.buffer.readline
read = sys.stdin.buffer.read

if sys.argv[-1] == "-t":
    print("testing")
    _test()
    sys.exit()

main()

Submission status: Accepted

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

numw = c.count('W')
numr = c.count('R')

ans = c[:numr].count('W')
print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

cnt_R = 0

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


ans = min(cnt_R, N - cnt_R)

cnt_swap = 0
for i in range(cnt_R):
    if C[i] != 'R':
        cnt_swap += 1


print(min(ans, cnt_swap))

Submission status: Accepted

Solution code:
N = int(input())
c = input()
l = 0
r = N-1
cnt = 0
while(l<r):
    if c[l] == "W" and c[r] == "R":
        cnt += 1
        l += 1
        r -= 1
    elif c[l] == "R":
        l += 1
    elif c[r] == "W":
        r -= 1
print(cnt)

Submission status: Accepted

Solution code:
from sys import stdin
from sys import setrecursionlimit
import bisect
setrecursionlimit(10 ** 7)

n = int(input())
c = input()

count = c.count("R")
point = 0

for i,j in enumerate(c,1):
    if j == "R":
        if i > count:
            point += 1

print(point)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n = int(input())
s = input()
k = s.count("R")
t = s[:k].count("R")
print(k-t)

Submission status: Accepted

Solution code:
n = int(input())
c = input()
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 = list(input())
ans = 0
l = 0
for i in range(N-1, -1, -1):
    if C[i] == 'R':
        while l < N and C[l] != 'W':
            l += 1
        if l > i or l == N:
            break
        C[i], C[l] = C[l], C[i]
        ans += 1
print(ans)

Submission status: Accepted

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

R = C.count("R") #赤の個数
ct = 0
for i in range(R):
  if C[i] == "W":
    ct += 1
print(ct)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
N = int(input())
c = list(input())

n_red = len([each for each in c if each=='R'])
n_red_in_left = len([c[i] for i in range(len(c)) if i<=n_red-1 and c[i]=='R'])

print(n_red-n_red_in_left)

Submission status: Accepted

Solution code:
import sys
stdin = sys.stdin
sys.setrecursionlimit(10**6)
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
nn = lambda: list(stdin.readline().split())
ns = lambda: stdin.readline().rstrip()

n = ni()
c = ns()
aw = c.count('W')
ans = min(n-aw,aw)
w = 0

for i in range(n):
    if c[i] == 'W': w+=1
    rw = aw-w
    rr = n-i-1-rw
    ans = min(ans, max(w,rr))

print(ans)

Submission status: Accepted

Solution code:
# import sys; input = sys.stdin.buffer.readline
# sys.setrecursionlimit(10**7)
from collections import defaultdict
con = 10 ** 9 + 7; INF = float("inf")

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

#処理内容
def main():
	N = int(input())
	c = input()
	rcnt = 0
	wcnt = 0
	for i in c:
		if i == "R":
			rcnt += 1
		else:
			wcnt += 1

	change = 0
	for i in range(N):
		if i < rcnt:
			if c[i] == "W":
				change += 1
		else:
			if c[i] == "R":
				change += 1

	ans = int(change // 2)
	print(ans)

if __name__ == '__main__':
	main()

Submission status: Accepted

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

r, w = 0, 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] == 'W':
        ans += 1

print(ans)

Submission status: Accepted

Solution code:
def examA():
    X = I()
    if X<30:
        ans = "No"
    else:
        ans = "Yes"
    print(ans)
    return

def examB():
    N, D = LI()
    cnt = 0
    for _ in range(N):
        x, y = LI()
        if x**2+y**2<=D**2:
            cnt += 1
    ans = cnt
    print(ans)
    return

def examC():
    N = 10**7
    K = I()
    cur = 0
    now = 1
    ans = -1
    for i in range(N):
        cur += 7 * now
        cur %= K
        if cur==0:
            ans = i+1
            break
        now *= 10
        now %= K
    print(ans)
    return

def examD():
    N = I()
    C = SI()
    cnt = 0
    l = 0; r = N-1
    while(l<r):
        while(l<N):
            if C[l]=="W":
                break
            l += 1
        while(0<=r):
            if C[r]=="R":
                break
            r -= 1
        if l<r:
            cnt += 1
            l += 1
            r -= 1
    ans = cnt
    print(ans)
    return

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

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

def test():
    i = I()
    li = LI()
    lsi = LSI()
    si = LS()
    print(i)
    print(li)
    print(lsi)
    print(si)
    return

from decimal import getcontext,Decimal as dec
import sys,bisect,itertools,heapq,math,random
from copy import deepcopy
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
def I(): return int(input())
def LI(): return list(map(int,sys.stdin.readline().split()))
def DI(): return dec(input())
def LDI(): return list(map(dec,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep,alphabet_convert
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = dec("0.000000000001")
alphabet = [chr(ord('a') + i) for i in range(26)]
alphabet_convert = {chr(ord('a') + i): i for i in range(26)}

getcontext().prec = 28

sys.setrecursionlimit(10**7)

if __name__ == '__main__':
    examD()

"""
142
12 9 1445 0 1
asd dfg hj o o
aidn
"""

Submission status: Accepted

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

l = 0
r = N-1
ans = 0
while True:
  while l<r and c[l]=="R":
    l += 1
  while l<r and c[r]=="W":
    r -= 1
  if l>=r:
    break
  l += 1
  r -= 1
  ans += 1
print(ans)

Submission status: Accepted

Solution code:
N=int(input())
c=input()
t=c.count("R")
p=c[:t].count("W")
print(p)

Submission status: Accepted

Solution code:
N = int(input())
C = input()
R = C.count("R")
print(C[:R].count("W"))

Submission status: Accepted

Solution code:
import sys
import math
from collections import deque

sys.setrecursionlimit(1000000)
MOD = 10 ** 9 + 7
input = lambda: sys.stdin.readline().strip()
NI = lambda: int(input())
NMI = lambda: map(int, input().split())
NLI = lambda: list(NMI())
SI = lambda: input()


def make_grid(h, w, num): return [[int(num)] * w for _ in range(h)]


def main():
    N = NI()
    S = SI()
    l = 0
    r = N - 1
    ans = 0
    if S.count("R") == 0 or S.count("R") == N:
        print(0)
        exit()

    while r - l >= 1:
        if S[l] == "W" and S[r] == "R":
            ans += 1
            l += 1
            r -= 1
        elif S[l] == "W":
            r -= 1
        elif S[r] == "R":
            l += 1
        else:
            l += 1
            r -= 1

    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

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

N = int(input())
c = input().rstrip()
white = [0] * N
red = [0] * N
if c[0] == 'W':
    white[0] = 1
for i in range(1, N):
    white[i] = white[i-1]
    if c[i] == 'W':
        white[i] += 1
for i in range(1, N)[::-1]:
    red[i-1] = red[i]
    if c[i] == 'R':
        red[i-1] += 1
if white[-1] == 0 or red[0] == 0:
    print(0)
    exit()
for i in range(N):
    if white[i] == red[i]:
        print(white[i])
        exit()

Submission status: Accepted

Solution code:
n = int(input())
s = input()
w,r = 0,0
for i in s:
    if i=='W':
        w+=1
    else:
        r+=1
cnt = 0
for i in range(r):
    if s[i]=='R':
        cnt+=1
print(r-cnt)

Submission status: Accepted

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

r = 0
for i in range(n):
    if C[i] == "R":
        r += 1

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()
rlist = []
wlist = []
for i in range(N):
    if c[i] == 'R':
        rlist.append(i)
    else:
        wlist.append(i)

cnt = 0
if len(rlist) == 0:
    print(0)
    exit()
for i in range(len(wlist)):
    if wlist[i] < rlist[-cnt - 1]:
        cnt += 1
    else:
        break
print(cnt)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import math
from functools import reduce
from collections import deque
import sys
sys.setrecursionlimit(10**7)

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

# スペース区切りの入力を読み込んで数値リストにして返します。
def get_nums_l():
    return [ int(s) for s in input().split(" ")]

# 改行またはスペース区切りの入力をすべて読み込んでイテレータを返します。
def get_all_int():
    return map(int, open(0).read().split())

def log(*args):
    print("DEBUG:", *args, file=sys.stderr)

def main():
    INF = 999999999999999999999999
    MOD = 10**9+7

    n = int(input())
    S = input()

    l = 0
    r = n-1
    ans = 0
    while l<r:
        while l<n and S[l] != "W":
            l += 1
        while r>0 and S[r] != "R":
            r -= 1
        # log(l,r)
        if l<r:
            ans += 1
        l+=1
        r-=1
    print(ans)

main()

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
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 LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

n=II()
s=SI()
allr=s.count("R")
lr=s[:allr].count("R")
print(allr-lr)

Submission status: Accepted

Solution code:
from itertools import accumulate

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

left_w = [0]
for c in s:
    if c == 'W':
        left_w.append(1)
    else:
        left_w.append(0)
left_w = list(accumulate(left_w))

right_r = [0]
for c in s[::-1]:
    if c == 'R':
        right_r.append(1)
    else:
        right_r.append(0)
right_r = list(accumulate(right_r))
right_r.reverse()

print(min(map(max, zip(left_w, right_r))))

Submission status: Accepted

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

wa = [0] * (n+2)
for i in range(n):
    if(c[i]=='W'): wa[i+1]+=1
for i in range(n+1):
    wa[i+1] += wa[i]

ans = n;
for i in range(n+2):
    w = wa[i]
    r = n-i - (wa[n] - wa[i])
    ans = min(ans, max(w, r))
print(ans)

Submission status: Accepted

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

r_cnt = 0
for c in C:
    r_cnt += c=='R'
ans = 0
for c in C[:r_cnt]:
    ans += c=='W'
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
C = list(input())
i = 0
j = N-1
cnt = 0
while i < j:
    if (C[j] == 'R') and (C[i] == 'W'):
        C[i], C[j] = C[j], C[i]
        i = i + 1
        j = j - 1
        cnt = cnt + 1
    elif (C[j] == 'R'):
        i = i + 1
    else:
        j = j - 1
print(cnt)

Submission status: Accepted

Solution code:
def main():
    n = int(input())
    s = input()
    r = s.count("R")
    cnt = 0
    for i in range(n-1, r-1, -1):
        if s[i] == "R":
            cnt += 1
    print(cnt)


main()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**8)
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()
red_cnt = 0
for s in S:
    if s == "R":
        red_cnt += 1
ans = 0
for s in S[:red_cnt]:
    if s == "W":
        ans += 1

print(ans)