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:
# Coding is about expressing your feeling and there is always a better way to express your feeling _feelme
import sys,math,numpy as np
#sys.stdin,sys.stdout=open('input.txt','r'),open('output.txt','w')
from sys import stdin,stdout;mod=int(1e9 + 7);from statistics import mode
from collections import *;from math import ceil,floor,inf,factorial,gcd,log2,sqrt
ii1=lambda:int(stdin.readline().strip())
is1=lambda:stdin.readline().strip()
iia=lambda:list(map(int,stdin.readline().strip().split()))
isa=lambda:stdin.readline().strip().split()
# print('{:.3f}'.format(1),round(1.123456789,4))
# np.set_printoptions(sign=' ',legacy='1.13') # legacy add space at sign position
# sys.setrecursionlimit(500000)
def lcm(a,b): return (a*b)//gcd(a,b)
def setbits(n):return bin(n).count('1')
def resetbits(n):return bin(n).count('0')
def modinv(n,p):return pow(n,p-2,p)
def ncr(n,r):
    num,den=1,1;r=min(n,n-r)
    for i in range(r):num*=(n-i);den*=(i+1)
    return num//den
def ncr_p(n, r, p):
    num,den=1,1;r=min(r,n-r)
    for i in range(r):num = (num * (n - i)) % p ;den = (den * (i + 1)) % p
    return (num * modinv(den,p)) % p
def isPrime(num) :
    if num<=1:return False
    if num==2 or n==3:return True
    if (num % 2 == 0 or num % 3 == 0) :return False
    m = int(num**0.5)+1
    for i in range(5,m,6):
        if (num % i == 0 or num % (i + 2) == 0) :return False
    return True
def bin_search(arr, low, high, val):
    while low <= high:
        mid = low + (high - low) // 2;
        if arr[mid] == val:return mid
        elif arr[mid] < val:low = mid + 1
        else:high = mid - 1
    return -1
def sumofdigit(num):
    count=0;
    while num : count+=num % 10;num //= 10;
    return count;
def inputmatrix():
    r,c=iia();mat=[0]*r;
    for i in range(r):mat[i]=iia();
    return r,c,mat;
def prefix_sum(n,arr):
    for i in range(1,n):arr[i]+=arr[i-1]
    return arr;
def binomial(n, k):
    if 0 <= k <= n:
        ntok = 1;ktok = 1
        for t in range(1, min(k, n - k) + 1):ntok *= n;ktok *= t;n -= 1
        return ntok // ktok
    else:return 0
def divisors(n):
    res = [];
    for i in range(1,ceil(sqrt(n))+1):
        if n%i == 0:
            if i==n//i:res.append(i)
            else:res.append(i);res.append(n//i)
    return res;


n = ii1()
s=is1()
a=Counter(s)
W=a['W']
R=a['R']
# print(W,R)
if W == n or R == n:
    print(0)
else:
    countr=0
    countw=0
    for i in range(R,n):
        if s[i]=='R':
            countr+=1
        else:
            countw+=1
    print(countr)

Submission status: Accepted

Solution code:
N = int(input())
S = input()
s_list = [s for s in S]
cnt = 0
r_cnt = s_list.count("R")
for i in range(r_cnt):
    if s_list[i] == "W":
        cnt += 1
print(cnt)

Submission status: Accepted

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

l = 0
r = len(S) - 1

W = 'W'
R = 'R'

cnt = 0
while l < r:
    if S[l] == R:
        l += 1
        continue
    else:
        while l < r:
            if S[r] == W:
                r -= 1
                continue
            else:
                cnt += 1
                l += 1
                r -= 1
                break

print(cnt)

Submission status: Accepted

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

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

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

print(wcount)

Submission status: Accepted

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

cntR = 0
for i in range(0,n):
	if(s[i]=="R"):
		cntR+=1

cntRL = 0
for i in range(0,cntR):
	if(s[i]=="R"):
		cntRL+=1

print(cntR-cntRL)

Submission status: Accepted

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

Submission status: Accepted

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

white = c.count("W")
ans = 0

for i in range(n):
    if white == 0:
        break
    else:
        if c[n - i - 1] == "R":
            ans += 1
            white -= 1
        elif c[n - i - 1] == "W":
            white -= 1

print(ans)

Submission status: Accepted

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

def alter(c,n):
    number = 0
    i = 0
    j = n-1
    while(i<j):
        if c[j] == 'R':
            j -= 1
            while (c[i] == 'R'):
                i += 1
                if i >= j:
                    return number
            number += 1
            i += 1
        else:
            j -= 1
    return number
    

    
print(alter(c,n))

Submission status: Accepted

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

cnt = 0
l = 0
r = n-1
while l < r:
    if c[l] == 'R':
        l += 1
    elif c[l] == 'W':
        if c[r] == 'R':
            c[l] = 'R'
            c[r] = 'W'
            cnt += 1
        else:
            r -= 1

print(cnt)

Submission status: Accepted

Solution code:
n = int(input())
c = input()
cw = c
cr = ''.join(list(reversed(c)))

#print(n)
#print(c)
#print(cw)
#print(cr)

ans = 0
w=0
r=0
nn = n

for i in range(n):
  nw = cw.find('W')
  if nw == -1:
    break
  nr = cr.find('R')
  if nr == -1:
    break
  if (nw + nr + 2) > nn:
    break
  nn = nn - (nw + nr + 2)
  cw = cw[(nw+1):]
  cr = cr[(nr+1):]
  ans +=1

  #  print(cw)
  #  print(cr)

print(ans)

Submission status: Accepted

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

ans = 0
sorted = N - 1
for i in range(N):
  if cs[i] == "W":
    for j in range(sorted, i, -1):
      sorted = j - 1
      if cs[j] == "R":
        cs[i], cs[j] = cs[j], cs[i]
        ans += 1
        break
  if (i + 1) > sorted:
    break
print(str(ans))

Submission status: Accepted

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


r = 0
w = 0
for x in c:
    if x == 'R':
        r += 1
    else:
        w += 1

if r == 0:
    print(0)
    exit()

ans = 0
for x in c:
    r -= 1
    if x =='W':
        ans += 1
    if r == 0:
        break    

print(ans)

Submission status: Accepted

Solution code:
import collections
N = int(input())
stones = list(input())
#print(stones)
c = collections.Counter(stones)
r_s = collections.Counter(stones[:c['R']])
print(c['R']-r_s['R'])

Submission status: Accepted

Solution code:
from collections import deque
n = int(input())
Cs = input()

#%%
widx = deque()
ridx = deque()
for i in range(n):
    if Cs[i] == 'W':
        widx.append(i)
    else:
        ridx.append(i)
#%%
cnt = 0
while True:
    if len(widx) == 0 or len(ridx) == 0:
        break
    elif widx[0] < ridx[-1]:
        widx.popleft()
        ridx.pop()
        cnt += 1
    else:
        break

print(cnt)

Submission status: Accepted

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

tmp = c.count('R')
tmp2 = c[:tmp].count('W')
tmp3 = c[tmp:].count('R')


if tmp2 > tmp3:
  print(tmp2*2-tmp3)
else:
  print(tmp3*2-tmp2)

Submission status: Accepted

Solution code:
from collections import Counter

n = int(input())
C = input()

c = Counter(C)

numR = 0

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

print(c['R']-numR)

Submission status: Accepted

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

s = sorted(c)

cnt = 0
for i, j in zip(c, s):
    if i != j:
        cnt += 1

print(cnt // 2)

Submission status: Accepted

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

rc = c.count('R')
ans = 0
for i in range(rc):
    if c[i] == 'W':
        ans += 1
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
c = str(input())
rc = c.count('R')
wc = c.count('W')
if rc ==0 or wc ==0:
  print('0')
else:
    s = c[:rc]
    wwc = s.count('W')
    print(wwc)

Submission status: Accepted

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

head = 0
tail = n-1
ans = 0
while head < n:
    if arr[head] == "R":
        head += 1
    else:
        break
while tail >= 0:
    if arr[tail] == "W":
        tail -= 1
    else:
        break
while head < tail:
    head += 1
    tail -= 1
    ans += 1
    while head < n:
        if arr[head] == "R":
            head += 1
        else:
            break
    while tail >= 0:
        if arr[tail] == "W":
            tail -= 1
        else:
            break

print(ans)

Submission status: Accepted

Solution code:
from collections import deque

n=int(input())
d=deque(list(input()))
#print(d)
r=0
while n>1:
  #print(d)
  tempr=False
  n-=1
  if d.pop()=="W":
    pass
  else:
    while n>0:
      n-=1
      if d.popleft()=="R":
        pass
      else:
        r+=1
        break
  #print(d,r)
print(r)

Submission status: Accepted

Solution code:
import sys
from math import sqrt, gcd, ceil, log
# from bisect import bisect, bisect_left
from collections import defaultdict, Counter, deque
# from heapq import heapify, heappush, heappop
input = sys.stdin.readline
read = lambda: list(map(int, input().strip().split()))

# sys.setrecursionlimit(5*10**6)

def main():
	n = int(input()); 
	# dic = defaultdict(int)
	# for i in range(1, 10):
	# 	for j in (1, 3, 7, 9):
	# 		dic[(j, (i*j)%10)] = i
	# # print(dic)
	# if n%10 in (1, 3, 7, 9):
	# 	t = n%10; i = 0
	# else:print(-1)
	s = list(input().strip())
	i, j = 0, n-1
	ans = 0
	while i < j:
		if s[i] == "W" and s[j] == "R":
			ans += 1
			s[i], s[j] = s[j], s[i]
		else:
			i += (s[i] == "R")
			j -= (s[j] == "W")
	print(ans)





if __name__ == "__main__":
	main()

Submission status: Accepted

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

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

nr = nw = 0 
nr = s.count('R')
nw = n-nr
ans = 0 

if nw == 0:
    print(ans)
    exit()

l = s[:nr]
ans = l.count('W')
print(ans)

Submission status: Accepted

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

Wcnt=0
for i in range(len(C)):
    if C[i]=="W":
        Wcnt+=1
ans=0
for i in range(N-Wcnt,N):
    if C[i]=="R":
        ans+=1
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
s = input()
l = list(s)
#n = len(l)
i = 0
j = n-1
cnt = 0
while(i < j):
    if l[i] == "W" and l[j] == "R":
        l[j] = 'W'
        l[i] = 'R'
        i = i+1
        j = j-1
        cnt = cnt+1
        continue

    if l[i] == "R":
        i = i+1

    if l[j] == "W":
        j = j-1


while(len(l) > 0):
    if l[-1] == "W":
        l.pop()
        continue

    if l[-1] == "R":
        break

k = "".join(l)
print(k.count("W")+cnt)

Submission status: Accepted

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

l = 0
r = n-1

c = 0

while l < r:
    while l < r and a[l] == 'R': l += 1
    while l < r and a[r] == 'W': r -= 1
    
    if a[l] == 'W' and a[r] == 'R':
        c += 1
        a[l] = 'R'
        a[r] = 'W'

print(c)

Submission status: Accepted

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

flag_left = 0
flag_right = N-1
counter = 0

ok = max(C.count("W"),C.count("R"))
if ok ==N:
    print(0)
    exit()

while flag_left<flag_right:
    while C[flag_left]=="R":
        flag_left += 1
        if flag_left>N-1:
            break
    while C[flag_right]=="W":
        flag_right -= 1
        if flag_left<0:
            break
        
    if flag_left<flag_right:
        counter += 1
    flag_left += 1
    flag_right -= 1
print(counter)

Submission status: Accepted

Solution code:
n=int(input())
word=input()
line=[]
for i in range(n):
    if(word[0]=='R'):
        line.append(1)
    else:
        line.append(0)
    word=word[1:]
x=0
y=n-1
ans=0
while(1):
    while(1):
        if(line[x]==0):
            break
        if(x>=y):
            break
        x+=1
    while(1):
        if(line[y]==1):
            break
        if(x>=y):
            break
        y-=1
    if(x>=y):
        break
    tmp=line[x]
    line[x]=line[y]
    line[y]=tmp
    ans=ans+1
print(ans)

Submission status: Accepted

Solution code:
import copy
N = input()
ls = list(input())

countR = ls.count('R')
ls2 = copy.copy(ls)
del ls2[countR:]
count = ls2.count('W')
print(count)

Submission status: Accepted

Solution code:
n = int(input())
c = list(input())
d = sorted(c)
count = 0
for i in range(n):
    if c[i] == 'W' and d[i] == 'R':
        count+=1
print(count)

Submission status: Accepted

Solution code:
n=int(input())
s=input()
if s.count('R')==n:
    print(0)
else:
    w=s.index('W')
    s=s[w:]
    a= s.count('W')
    b=s[len(s)-a:].count('W')
    print(a-b)

Submission status: Accepted

Solution code:
N = int(input())

c = list(input())

cnt = 0
headcnt = 0
tailcnt = -1

Noflag = 0

while True:
    if c[tailcnt] == 'R' and Noflag == 0:
        while True:
            if c[headcnt] == 'W':
                c[headcnt], c[tailcnt] = c[tailcnt], c[headcnt]
                cnt += 1
                # headcnt += 1
                # tailcnt -= 1
                break
            else:
                headcnt += 1
                if headcnt + abs(tailcnt) >= len(c):
                    Noflag += 1
                    break
    elif c[tailcnt] == 'W' or Noflag == 1:
        tailcnt -= 1
        if headcnt + abs(tailcnt) >= len(c):
            print(cnt)
            break

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys

input_methods=['clipboard','file','key']
using_method=0
input_method=input_methods[using_method]

tin=lambda : map(int, input().split())
lin=lambda : list(tin())
mod=1000000007

#+++++

def main():
	n = int(input())
	#b , c = tin()
	s = input()
	r_num = sum([1 for c in s if c == 'R'])
	w_num = n-r_num
	ret = 0
	for c in s[:r_num]:
		if c == 'W':
			ret += 1
			
			
	print(ret)
	
	
	
#+++++
isTest=False

def pa(v):
	if isTest:
		print(v)
		
def input_clipboard():
	import clipboard
	input_text=clipboard.get()
	input_l=input_text.splitlines()
	for l in input_l:
		yield l

if __name__ == "__main__":
	if sys.platform =='ios':
		if input_method==input_methods[0]:
			ic=input_clipboard()
			input = lambda : ic.__next__()
		elif input_method==input_methods[1]:
			sys.stdin=open('inputFile.txt')
		else:
			pass
		isTest=True
	else:
		pass
		#input = sys.stdin.readline
			
	ret = main()
	if ret is not None:
		print(ret)

Submission status: Accepted

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

Submission status: Accepted

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

first_r = -1
rcount = C.count('R')
wcount = C.count('W')
rcount_org = copy.deepcopy(rcount)
rlen = 0
ans = 0

if rcount == 0 or wcount == 0:
  print(0)
  exit()
  
for i, c in enumerate(C):
  if c == 'R':
    rcount -= 1
    rlen += 1
  
  if c == 'W':
    rcount -= 1
    rlen += 1
    ans += 1
    
  if rlen == rcount_org:
    print(ans)
    exit()
    
  #print(i, rcount, rlen)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)

n = int(input())
s = input().strip()

from collections import deque

red_pos = deque([])
white_pos = deque([])
for i, v in enumerate(s):
    if v == 'R':
        red_pos.append(i)
    else:
        white_pos.append(i)

ans = 0
while True:
    if len(red_pos) == 0 or len(white_pos) == 0:
        break
    if red_pos[-1] < white_pos[0]:
        break
    ans += 1
    white_pos.popleft()
    red_pos.pop()

print(ans)

Submission status: Accepted

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

pos_r = set()
for i in range(n):
    if c[i] == 'R':
        pos_r.add(i)

ans = 0
num_r = len(pos_r)
for ri in pos_r:
    if ri >= num_r:
        ans += 1
print(ans)

Submission status: Accepted

Solution code:
from collections import deque
N = int(input())
A = list(input())
R = deque()
W = deque()
for i in range(N):
    if A[i] == "R":
        R.append(i)
    else:
        W.append(i)

        
ans = 0        
for i in range(N):
    if len(R) * len(W) == 0:
        print(0)
        break
    else:
        a = R.pop()
        b = W.popleft()
        if a < b:
            print(ans)
            break
        else:
            R.appendleft(b)
            W.append(a)  
            ans += 1

Submission status: Accepted

Solution code:
n = int(input())
c = list(input())
sc = sorted(c)

if sc[0] == "W" or sc[-1] == "R":
    print(0)
    
else:
    for i in range(n):
        if sc[i] == "W":
            W_start = i
            break

    W_in_R = 0

    for i in c[:W_start]:
        if i == "W":
            W_in_R += 1

    R_in_W = 0

    for i in c[W_start:]:
        if i == "R":
            R_in_W += 1

    print(max(W_in_R , R_in_W))

Submission status: Accepted

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

i = 0
j = N-1
while i < j:
    while True:
        # print(1, i, j)
        if i == j:
            break
        if c[i] == 'W':
            break
        i += 1
    while True:
        # print(2, i, j)
        if i == j:
            break
        if c[j] == 'R':
            ans += 1
            break
        j -= 1
    i += 1
    j -= 1
print(ans)

Submission status: Accepted

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


# 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():
    N = int(input())
    c = list(input())
    nR = c.count("R")
    nW = c.count("W")
    # print(c)
    rightR = c[nR:].count("R")
    leftW = c[:nR].count("W")
    print(max(rightR,leftW))

if __name__ == '__main__':
    main()

Submission status: Accepted

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

def main():
    input = sys.stdin.readline
    n = int(input())
    c = list(input())
    left = 0
    right = n - 1
    ans = 0
    while True:
        if c[left] == "R" and left < n - 1:
            left += 1
        if c[right] == "W" and right > 0:
            right -= 1
        if right <= left:
            print(ans)
            break
        if c[left] == "W" and c[right] == "R":
            c[left] = "R"
            c[right] = "W"
            ans += 1
        """
        if c[left] == "W":
            c[left] = "R"
            ans += 1
        if c[right] == "R":
            c[right] = "W"
            ans += 1
        """



if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
    N = input()
    CS = [c for c in input().strip()]

    wtotal = 0
    rtotal = 0
    for c in CS:
        if c == "W":
            wtotal += 1
        elif c == "R":
            rtotal += 1
        else:
            raise Exception()

    left = -1
    right = len(CS)

    op = 0
    w = 0
    r = 0
    while True:
        # print(f"L:{left}  R:{right}  w:{w}  r:{r}  op:{op}")
        if w > r:
            right -= 1
            if CS[right] == "R":
                r += 1
        else:
            left += 1
            if CS[left] == "W":
                w += 1

        if w > 0 and r > 0:
            op += 1
            w -= 1
            r -= 1

        if right == left or right == 0 or left == len(CS) - 1:
            break

    change = op
    print(min(wtotal, rtotal, change))


main()

Submission status: Accepted

Solution code:
import sys
import math
import itertools
import collections
import heapq
import re
import numpy as np
from functools import reduce

rr = lambda: sys.stdin.readline().rstrip()
rs = lambda: sys.stdin.readline().split()
ri = lambda: int(sys.stdin.readline())
rm = lambda: map(int, sys.stdin.readline().split())
rl = lambda: list(map(int, sys.stdin.readline().split()))
inf = float('inf')
mod = 10**9 + 7

n = ri()
s = rr()
cnt = 0
i = 0
j = n-1
while True:
    while s[i] == 'R':
        i += 1
        if i >= n:
            break
    while s[j] == 'W':
        j -= 1
        if j < 0:
            break
    if i < j:
        cnt += 1
        i += 1
        j -=1
    else:
        break
print(cnt)

Submission status: Accepted

Solution code:
import sys
import re
import math
import collections
import bisect
import itertools
import fractions
import functools
import copy
import heapq
import decimal
import statistics
import queue

# import numpy as np

sys.setrecursionlimit(10 ** 9)
INF = 10 ** 16
MOD = 10 ** 9 + 7
# MOD = 998244353

ni = lambda: int(sys.stdin.readline())
ns = lambda: map(int, sys.stdin.readline().split())
na = lambda: list(map(int, sys.stdin.readline().split()))
na1 = lambda: list(map(lambda x: int(x) - 1, sys.stdin.readline().split()))


# ===CODE===


def main():
    n = ni()
    c = list(input())

    w = 0
    tw = 0
    r = c.count("R")

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

    lastw = 0
    tmp = 0
    for i in range(n):
        if r == 0:
            break

        if c[i] == "W":
            r -= 1
            lastw += 1
        else:
            r -= 1

    print(lastw)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
import math
import numpy as np
def I():return int(sys.stdin.readline().replace("\n",""))
def I2():return map(int,sys.stdin.readline().replace("\n","").split())
def S():return str(sys.stdin.readline().replace("\n",""))
def L():return list(sys.stdin.readline().replace("\n",""))
def Intl():return [int(k) for k in sys.stdin.readline().replace("\n","").split()]
def Lx(k):return list(map(lambda x:int(x)*-k,sys.stdin.readline().replace("\n","").split()))

if __name__ == "__main__":
    n = I()
    s = S()
    cnt = 0
    for i in range(s.count("R")):
        if s[i] == "W":cnt += 1
    s = s[::-1]
    for i in range(s.count("W")):
        if s[i] == "R":cnt += 1
    print(cnt//2)

Submission status: Accepted

Solution code:
n = int(input())
cs = input()
cnt = 0
i = 0
j = n-1
while(1):
  if i >= j:
    break
  if cs[i] == "R":
    i += 1
  if cs[j] == "W":
    j -= 1
  if cs[i] == "W" and cs[j] == "R":
    cnt += 1
    i += 1
    j -= 1
      
print(cnt)

Submission status: Accepted

Solution code:
N=int(input())
A=input()
ans=0
lindex=0
rindex=N-1
flag=0#0:左進行,1:右進行,2:両どまり
while(1):
    if lindex>=rindex:
        break
    if flag==0:
        if A[lindex]=="W":
            flag=1
        else:
            lindex+=1

    elif flag==1:
        if A[rindex]=="R":
            flag=2
        else:
            rindex-=1
    
    else:
        ans+=1
        flag=0
        lindex+=1
        rindex-=1
#if flag==1 :
#    ans+=1
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
colors = input()
data = [int(c == 'R') for c in colors]

lm = 0
rm = sum(data)
min_move = rm

for i in range(N):
    if data[i]:
        rm -= 1
    else:
        lm += 1
    move = min(lm, rm) + abs(lm - rm)
    min_move = min(min_move, move)

print(min_move)

Submission status: Accepted

Solution code:
import re
import sys
import math
import itertools
import bisect
from copy import copy
from collections import deque,Counter
from decimal import Decimal
import functools
def v(): return input()
def k(): return int(input())
def S(): return input().split()
def I(): return map(int,input().split())
def X(): return list(input())
def L(): return list(input().split())
def l(): return list(map(int,input().split()))
def lcm(a,b): return a*b//math.gcd(a,b)
sys.setrecursionlimit(10 ** 9)
mod = 10**9+7
cnt = 0
ans = 0
inf = float("inf")

n=k()
s=X()
p=[1 if i=="W" else 0 for i in s]
a = s.count("R")
x = p[:a]
print(sum(x))

Submission status: Accepted

Solution code:
N = int(input())
c = input()
total_r = 0
total_w = 0
ans = 0
for i in range(len(c)):
    if c[i] == 'R':
        total_r += 1
    else:
        total_w += 1
for i in range(total_r):
    if c[i] == "W":
        ans += 1
print(ans)

Submission status: Accepted

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


ans = 10**6
r = [0]
w = [0]

for i in range(n):
    r.append(r[i] + (s[i] == "R"))
    w.append(w[i] + (s[i] == "W"))

# print(r)
# print(w)

for i in range(n + 1):
    mi = min(w[i], r[-1] - r[i])
    ma = max(w[i], r[-1] - r[i])
    # print(i, mi, ma)
    # mi = min(r[i], w[-1])
    # ma = max(w[i], r)
    # ans = min(ans, i - w[i] + (r[-1] - r[i]))
    ans = min(ans, mi + (ma-mi))

print(ans)

Submission status: Accepted

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

r = c.count("R")
w = c.count("W")

if r == 0 or w == 0:
    print(0)
else:
    print(c[0:r].count("W"))

Submission status: Accepted

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

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

for i in range(r):
    if c[i] == "R":
        continue
    else:
        ans += 1

print(ans)

Submission status: Accepted

Solution code:
N=int(input())
c=input()
C=[]
for i in range(N):
    C.append(c[i])
num= C.count("W")
CC=C[(N-num):]
numnum=CC.count("W")
print(num-numnum)

Submission status: Accepted

Solution code:
### ----------------
### ここから
### ----------------

import sys
from io import StringIO
import unittest

def yn(b):
    print("Yes" if b==1 else "No")
    return

def resolve():
    readline=sys.stdin.readline

    #n,m,k=map(int, readline().rstrip().split())
    #arr=list(map(int, readline().rstrip().split()))
    n=int(readline())
    ss=readline().rstrip()
    j=len(ss)
    ans=0
    if j==1:
        print(0)
        return
    for i in range(len(ss)):
        if ss[i]=="W":
            j-=1
            if j >= 0:
                while ss[j]!="R":
                    j-=1
                    if j < 0:
                        break
            if j > i:
                ans+=1
    print(ans)

    return

if 'doTest' not in globals():
    resolve()
    sys.exit()

### ----------------
### ここまで 
### ----------------

Submission status: Accepted

Solution code:
n = int(input())
s = input()
cw = 0
lol = 0
for i in s:
    if i == 'W':
        cw += 1
for i in range(n-1,n-cw-1,-1):
    if s[i] == 'W':
        lol += 1
print(abs(lol-cw))

Submission status: Accepted

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

isiall = min(saidan.count('W'), saidan.count('R'))

tesuu = 0
for i in range(len(saidan)//2):
    r_iti = saidan.rfind('R')
    w_iti = saidan.find('W')
    
    if r_iti == -1 or w_iti == -1 or r_iti < w_iti:
        break
    
    saidan = saidan[w_iti+1 : r_iti]
    tesuu += 1
    
print(min(tesuu, isiall))

Submission status: Accepted

Solution code:
import collections
def main():
    N = int(input())
    S = list(input())
    if len(set(S))==1:
        print(0)
        return
    cnt = 0
    left = 0
    right = len(S)-1
    while left<right:
        while left<len(S) and S[left]=='R':
            left += 1
        while right>=0 and S[right] == 'W':
            right -=1
        if left<right and S[left] == 'W':
            cnt +=1
            left += 1
            right -=1
    print(cnt)
    return 0
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# Q4
import bisect,collections,copy,heapq,itertools,math,numpy,string
import sys
from functools import lru_cache

def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())

N = I()
C = S()

rest_R = C.count("R")
index = 0
operation = 0

while True:
    if rest_R == 0:
        break
    current = C[index]
    if current == "R":
        rest_R -= 1
        index += 1
    else:
        operation += 1
        rest_R -= 1
        index += 1

print(operation)

Submission status: Accepted

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

ans = 0
left = 0
right = N -1
while left < right:
    if C[right] == "W":
        right -= 1
        continue
    if C[left] == "R":
        left += 1
        continue
    if C[left] == "W" and C[right] == "R":
        ans += 1
        right -= 1
        left += 1

print(ans)

Submission status: Accepted

Solution code:
import numpy as np

N=int(input())
C=np.array([x for x in input()])

if np.count_nonzero(C=='W')==N:
  print(0)
else:
  R_count=np.count_nonzero(C=='R')
  print(np.count_nonzero(C[:R_count]=='W'))

Submission status: Accepted

Solution code:
N = int(input())
S = input()
cnt_w = S.count("W")
cnt_r = S.count("R")
cl_chg = min(cnt_w, cnt_r)

sw = S[:cnt_r].count("W")
sr = S[cnt_r:].count("R")
swap = min(sw, sr)
print(min(cl_chg, swap))

Submission status: Accepted

Solution code:
n = int(input())
c = str(input())
cn = [False]*n
for i in range(n):
    if c[i]=="R":
        cn[i]= True


ans = 0
k=n-1
b=0

for i in range(n):
    if b==1:
        break

    if not(cn[i]):
        for j in range(k,0,-1):

            if cn[j]:
                k =j-1
                if i < j:
                    #cn[i]=True
                    #cn[j]=False
                    ans +=1
                    break
            if i>=j:
                b=1
                break
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
c = input()
rl = [ i for i,_ in enumerate(c) if _ == 'R' ]

cnt = 0
loc = 0
rid = -1
while True:
	try:
		if c[loc] == 'W':
			rloc = rl[rid]
			rid -= 1
			if rloc < loc:
				break
			else:
				cnt += 1
		loc += 1
		if loc == n:
			break
		#print(c,cnt)
	except:
		break
print(cnt)

Submission status: Accepted

Solution code:
N = int(input())

stones = input()

N = len(stones)

l = 0
r = N - 1

cnt = 0

while r - l > 0:
    while stones[l] != 'W' and r - l > 0:
        l += 1

    while stones[r] != 'R' and r - l > 0:
        r -= 1

    if r - l > 0:
        cnt += 1
        l += 1
        r -= 1
    else:
        break

print(cnt)

Submission status: Accepted

Solution code:
import sys
N = int(input())
c = input()
ans = 0
exchange = 0
for i in range(N):
    if c[i] == "W":
        exchange = i
        break
else:
    print(0)
    sys.exit()

for i in range(N):
    if N-i > exchange:
        if c[-(i+1)] =="R":
            # c = list(c)
            # c[exchange] = "R"
            # c[-(i+1)] = "W"
            # c = "".join(c)
            # c = c[:exchange]+"R"+c[exchange+1:]
            # print("newc=",c)
            # c = c[:-(i+1)]+"W"+c[N-i:]
            # print("newc=",c)
            ans += 1
            for k in range(exchange+1,N-(i+1)):
                if c[k] == "W":
                    exchange = k
                    break
            else:
                break
    else:
        break
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
s=input()
l=[0]
for i in range(n):
    l.append(l[i]+(s[i]=="R"))
ans=n
#print(l)
for i in range(n+1):
    ans=min(ans,abs(l[i]-i)+abs(l[-1]-l[i]))
    #print(ans,i)
    if i==l[-1]:
        ans=min(ans,abs(l[i]-i))
        #print(ans)
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
alis = list(input())
t = alis.count("R")
print(alis[0:t].count("W"))