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 sys
# input = sys.stdin.readline
# import re
import collections

def main():
    n = int(input())
    s = input()
    sc = collections.Counter(s)
    # 半分ずつの場合
    if sc['W'] == sc['R']:
        # 右側のRをカウント
        print(s[n//2:].count('R'))
        exit()
    print(s[:sc['R']].count('W'))


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


def input_list_str():
    return list(map(str, input().split()))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#ceilevenoddformula
import math
from queue import PriorityQueue
import bisect
import copy
import time
from collections import Counter
#map(int,input().split())
#int(x) for x in input().split()
n=int(input())
x=input()
x=list(x)
w=0
f=0
a=0
r=n-1
ans=min(x.count('W'),x.count('R'))
while w<=r:
	if x[w]=='W' and x[r]=='R':
		w+=1
		r-=1
		a+=1
	elif x[w]=='R':
		w+=1
	elif x[r]=='W':
		r-=1

print(min(a,ans))

Submission status: Accepted

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

r_cnt = c.count('R')
w_cnt = c.count('W')

cnt = 0

for i in range(r_cnt):
    if c[i] == 'R':
        continue
    else:
        cnt += 1

print(cnt)

Submission status: Accepted

Solution code:
# ANSHUL GAUTAM
# IIIT-D

from math import *
from copy import *                      # ll = deepcopy(l)
from heapq import *                     # heappush(hp,x)
from string import *                    # alpha = ascii_lowercase
from random import *                    # l.sort(key=lambda l1:l1[0]-l1[1]) => ex: sort on the basis difference
from bisect import *                    # bisect_left(arr,x,start,end)  => start and end parameters are temporary
from sys import stdin                   # bisect_left return leftmost position where x should be inserted to keep sorted
from sys import maxsize                 # minn = -maxsize
from operator import *                  # d = sorted(d.items(), key=itemgetter(1))
from itertools import *                 # pre = [0] + list(accumulate(l))
from decimal import Decimal             # a = Decimal(a)    # use this for math questions
from collections import Counter         # d = dict(Counter(l))
from collections import defaultdict     # d = defaultdict(list)

'''
8
WRWWRWRR
'''

def solve(l):
	l = list(l)
	n = len(l)
	if(len(set(l)) == 1):
		return 0
	m1 = l.count('R')
	m2,m3,m4,m5 = 0,0,l.count('W'),l.count('R')
	f = 0
	for i in range(n):
		if(f and l[i] == 'R'):
			m2 += 1
		elif(l[i] == 'W'):
			f = 1
	reds = l.count('R')
	rs = 0
	for i in range(reds):
		if(l[i] == 'R'):
			rs += 1
	m3 = reds - rs
	# print(m1,m2,m3,m4,m5)
	return min(m1,m2,m3,m4,m5)
	

N = int(stdin.readline())
l = input()
ans = solve(l)
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
s = input()
fir = True
f = 0
b = len(s)-1
count = 0
while(b > f):
    if(s[f] == "R"):
        f += 1
        continue
    elif(s[b] == "R"):
        count += 1
        f += 1
        b -= 1
        continue
    elif(s[b] == "W"):
        b -= 1
print(count)

Submission status: Accepted

Solution code:
N = int(input())
C = input()
Nw = C.count('W')
Nr = N - Nw
print(Nw - C[(-1*Nw):].count('W'))

Submission status: Accepted

Solution code:
def resolve():
    N = int(input())
    C = list(input())
    rnum = 0
    for c in C:
        if c == "R":
            rnum += 1
    leftr = 0
    for c in C[:rnum]:
        if c == "R":
            leftr += 1
    print(rnum-leftr)
    

if '__main__' == __name__:
    resolve()

Submission status: Accepted

Solution code:
## necessary imports
import sys
input = sys.stdin.readline
# from math import ceil, floor, factorial;

def ceil(x):
    if x != int(x):
        x = int(x) + 1;
    return x;
    
# swap_array function
def swaparr(arr, a,b):
    temp = arr[a];
    arr[a] = arr[b];
    arr[b] = temp;

## gcd function
def gcd(a,b):
    if b == 0:
        return a;
    return gcd(b, a % b);

## nCr function efficient using Binomial Cofficient
def nCr(n, k): 
    if(k > n - k): 
        k = n - k; 
    res = 1;
    for i in range(k): 
        res = res * (n - i);
        res = res / (i + 1); 
    return int(res);

## upper bound function code -- such that e in a[:i] e < x;
def upper_bound(a, x, lo=0, hi = None):
    if hi == None:
        hi = len(a);
    while lo < hi:
        mid = (lo+hi)//2;
        if a[mid] < x:
            lo = mid+1;
        else:
            hi = mid;
    return lo;

## prime factorization
def primefs(n):
    ## if n == 1    ## calculating primes
    primes = {}
    while(n%2 == 0 and n > 0):
        primes[2] = primes.get(2, 0) + 1
        n = n//2
    for i in range(3, int(n**0.5)+2, 2):
        while(n%i == 0 and n > 0):
            primes[i] = primes.get(i, 0) + 1
            n = n//i
    if n > 2:
        primes[n] = primes.get(n, 0) + 1
    ## prime factoriazation of n is stored in dictionary
    ## primes and can be accesed. O(sqrt n)
    return primes

## MODULAR EXPONENTIATION FUNCTION
def power(x, y, p): 
    res = 1
    x = x % p  
    if (x == 0) : 
        return 0
    while (y > 0) : 
        if ((y & 1) == 1) : 
            res = (res * x) % p 
        y = y >> 1      
        x = (x * x) % p 
    return res 

## DISJOINT SET UNINON FUNCTIONS
def swap(a,b):
    temp = a
    a = b
    b = temp
    return a,b;

# find function with path compression included (recursive)
# def find(x, link):
#     if link[x] == x:
#         return x
#     link[x] = find(link[x], link);
#     return link[x];

# find function with path compression (ITERATIVE)
def find(x, link):
    p = x;
    while( p != link[p]):
        p = link[p];
    
    while( x != p):
        nex = link[x];
        link[x] = p;
        x = nex;
    return p;


# the union function which makes union(x,y)
# of two nodes x and y
def union(x, y, link, size):
    x = find(x, link)
    y = find(y, link)
    if size[x] < size[y]:
        x,y = swap(x,y)
    if x != y:
        size[x] += size[y]
        link[y] = x

## returns an array of boolean if primes or not USING SIEVE OF ERATOSTHANES
def sieve(n): 
    prime = [True for i in range(n+1)] 
    p = 2
    while (p * p <= n): 
        if (prime[p] == True): 
            for i in range(p * p, n+1, p):
                prime[i] = False
        p += 1
    return prime

#### PRIME FACTORIZATION IN O(log n) using Sieve ####
MAXN = int(1e5 + 5)
def spf_sieve():
    spf[1] = 1;
    for i in range(2, MAXN):
        spf[i] = i;
    for i in range(4, MAXN, 2):
        spf[i] = 2;
    for i in range(3, ceil(MAXN ** 0.5), 2):
        if spf[i] == i:
            for j in range(i*i, MAXN, i):
                if spf[j] == j:
                    spf[j] = i;
    ## function for storing smallest prime factors (spf) in the array

################## un-comment below 2 lines when using factorization #################
# spf = [0 for i in range(MAXN)]
# spf_sieve();
def factoriazation(x):
    ret = {};
    while x != 1:
        ret[spf[x]] = ret.get(spf[x], 0) + 1;
        x = x//spf[x]
    return ret;
    ## this function is useful for multiple queries only, o/w use
    ## primefs function above. complexity O(log n)

## taking integer array input
def int_array():
    return list(map(int, input().strip().split()));

def float_array():
    return list(map(float, input().strip().split()));

## taking string array input
def str_array():
    return input().strip().split();

#defining a couple constants
MOD = int(1e9)+7;
CMOD = 998244353;
INF = float('inf'); NINF = -float('inf');

################### ---------------- TEMPLATE ENDS HERE ---------------- ###################


## either make em'all white.. yeah KKK style .. lol
## either make string like RRRRRWWWWWWWWWW, i.e. all reds than white;
## either make string like RRRRRRRRRRRRRRR .... all reds.. fucking rednecks;

n = int(input()); s = input().strip();
ans = min(s.count('R'), s.count('W'));

w = s.count('W'); cnt = 0;
for i in range(n - w):
    if s[i] == 'W':
        cnt += 1;
r = s.count('R');

if cnt <= r:
    ans2 = cnt;
else:
    ans2 = cnt*2 - r;
ans = min(ans2, ans);
print(ans);

Submission status: Accepted

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

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

res = [0 for _ in range(N+1)]
for i in range(1, N+1):
    if S[i-1] == 'R':
        res[i] = res[i-1] + 1
    else:
        res[i] = res[i-1]

print(r-res[r])

Submission status: Accepted

Solution code:
import sys
from io import StringIO
import unittest
import os

# 再帰処理上限(dfs作成時に設定するのが面倒なので限度近い値を組み込む)
sys.setrecursionlimit(999999999)


# 実装を行う関数
def resolve(test_def_name=""):
    n = int(input())
    rw_s = list(input())

    count = rw_s.count("R")
    acted = rw_s[0:count].count("R")

    print(count - acted)


# テストクラス
class TestClass(unittest.TestCase):
    def assertIO(self, assert_input, output):
        stdout, sat_in = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(assert_input)
        resolve(sys._getframe().f_back.f_code.co_name)
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, sat_in
        self.assertEqual(out, output)

    def test_input_1(self):
        test_input = """4
WWRR"""
        output = """2"""
        self.assertIO(test_input, output)

    def test_input_2(self):
        test_input = """2
RR"""
        output = """0"""
        self.assertIO(test_input, output)

    def test_input_3(self):
        test_input = """8
WRWWRWRR"""
        output = """3"""
        self.assertIO(test_input, output)

    # 自作テストパターンのひな形(利用時は「tes_t」のアンダーバーを削除すること
    def tes_t_1original_1(self):
        test_input = """データ"""
        output = """データ"""
        self.assertIO(test_input, output)


# 実装orテストの呼び出し
if __name__ == "__main__":
    if os.environ.get("USERNAME") is None:
        # AtCoder提出時の場合
        resolve()

    else:
        # 自PCの場合
        unittest.main()

Submission status: Accepted

Solution code:
def main():
    import sys
    def input(): return sys.stdin.readline().rstrip()
    
    n = int(input())
    c = input()

    s = 0
    e = n-1
    cnt = 0
    while s < e:
        while c[s] != 'W' and s < e:
            s+= 1
        
        while c[e] != 'R' and s < e:
            e -= 1
        if c[e] != c[s]:
            cnt += 1
        s+= 1
        e -= 1
    print(cnt)

        

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def _run(N, colors):
    count = 0
    head_i = 0
    tail_i = N - 1
    while head_i < tail_i:
        if colors[head_i] == "W" and colors[tail_i] == "R":
            count += 1
            head_i += 1
            tail_i -= 1
        else:
            if colors[head_i] != "W":
                head_i += 1
            if colors[tail_i] != "R":
                tail_i -= 1

    print(count)


def _main():
    N = int(input())
    colors = str(input())
    _run(N, colors)


if __name__ == "__main__":
    _main()

Submission status: Accepted

Solution code:
import sys
N = int(input())
c = list(input())
#print(c)
myr_cnt = c.count('R')
if myr_cnt == 0:
    print(0)
    sys.exit()
#print(myr_cnt)
myw_cnt = 0
for i in range(myr_cnt):
    if c[i] == 'W':
        myw_cnt += 1
print(myw_cnt)

Submission status: Accepted

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

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

print(r - ms)

Submission status: Accepted

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

cnt_r = c.count("R")

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

Submission status: Accepted

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

C_list = list(C)

W_count = C_list.count('W')
R_count = C_list.count('R')

tmp = ['R']*R_count + ['W']*W_count

ans = 0

for i in range(N):
    if C_list[i] != tmp[i]:
        ans += 1
        
print(ans//2)

Submission status: Accepted

Solution code:
N = int(input())
C = str(input())
count = C.count("R")
ans = 0

for i in range(count):
  if C[i] == "W":
    ans += 1

print(ans)

Submission status: Accepted

Solution code:
if __name__ == '__main__':
	N = int(input())
	S = input()
	L = 0
	R = N-1
	count = 0
	if S.count('W') == 0 or S.count('R') == 0:
		R = -1
	while(L < R):
		while(S[L] == 'R'):
			L += 1
		while(S[R] == 'W'):
			R -= 1
		if L > R:
			break
		L += 1
		R -= 1
		count += 1

	print(count)

Submission status: Accepted

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

def solve():
    N = int(input())
    Cs = input()

    ans = 0
    left, right = 0, N-1
    while left <= right:
        if Cs[left]=="W" and Cs[right]=="R":
            ans += 1  # 石を入れ替える
            left, right = left+1, right-1
            continue
        elif Cs[left]=="W" and Cs[right]=="W":
            right -= 1
            continue
        elif Cs[left]=="R" and Cs[right]=="R":
            left += 1
            continue
        else:
            left, right = left+1, right-1
            continue


    print(ans)


if __name__ == "__main__":
    solve()

Submission status: Accepted

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

l = 0
r = n-1
ans = 0
while(True):
    while(s[l]=='R' and l<n-1):
        l+=1
    while(s[r]=='W' and 0<r):
        r-=1
    if l < r:
        ans += 1
        l += 1
        r -= 1
    else:
        break

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
c = input()
s2 = "".join(sorted(list(c)))
ans = 0
for i in range(n):
    ans += 1 if c[i] != s2[i] else 0
print(ans // 2)

Submission status: Accepted

Solution code:
n=int(input())
if n==0:
	exit()
st=input()
r=st.count("R")
print(st[:r].count("W"))

Submission status: Accepted

Solution code:
N = int(input())
c = list(input())
sousa = 0
w = 0
r = N-1

for i in range(N):
    if c[w] == 'W' and c[r] == 'R':
        c[w] = 'R'
        c[r] = 'W'
        r -= 1
        w += 1
        sousa += 1
    elif c[w] == 'W':
        r -= 1
    elif c[r] == 'R':
        w += 1
    else:
        r -= 1
        w += 1
    if w >= r:
        break

print(sousa)

Submission status: Accepted

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

def solve(s,n):
    if "W" not in s or "R" not in s or s.find("WR")==-1:
        return 0

    else:
        arr=list(s)
        i=0
        j=n-1
        count=0

        while i<j:
            if arr[i]=="W" and arr[j]=="R":
                count += 1
                i+=1
                j-=1

            elif arr[i]=="W" and arr[j]=="W":
                j-=1
            elif arr[i]=="R" and arr[j]=="R":

                i+=1
            else:
                i+=1
                j-=1
        return count
print(solve(s,n))

Submission status: Accepted

Solution code:
N = int(input())
c = list(input())
R = 0
for i in c:
    if i == 'R':
        R +=1
r = 0
for i in range(0,R):
    if c[i] == 'R':
        r +=1
print(R-r)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n=int(input())
c=input()
a=c.count("R")
d=c[:a]
b=d.count("R")
print(a-b)

Submission status: Accepted

Solution code:
from heapq import heapify, heappush, heappop

def main(C):
    R = []
    W = []
    for i, c in enumerate(C):
        if c == 'R':
            R.append(-i)
        else:
            W.append(i)
    if len(R)==0 or len(W)==0:
        return 0
    heapify(R)  #マイナスで保持する
    heapify(W)
    cnt = 0
    while True:
        #print(R, W)
        r_last = -heappop(R)
        w_first = heappop(W)
        if r_last < w_first:
            break
        heappush(R, -w_first)
        heappush(W, r_last)
        cnt += 1
    return cnt
    

if __name__ == "__main__":
    N = int(input())
    C = input()
    ans = main(C)
    print(ans)

Submission status: Accepted

Solution code:
N,c = open(0).read().split()
N = int(N)
white_right = 0
red = 0
red_left = 0
for x in c:
    if x == 'R':
        red_left += 1
    else:
        break
c_altered = c[red_left:]
l = len(c_altered)
for x in c_altered:
    if x == 'R':
        red += 1
        white_right = 0
    else:
        white_right += 1
c_altered = c_altered[:l-white_right]
l = len(c_altered)
ans1 = red
ans2 = c_altered[:red].count('W')
print(min(ans1,ans2))

Submission status: Accepted

Solution code:
n = int(input())
s = input()
s = list(map(lambda x: 1 if x == 'R' else 0,s))
ans = min(s.count(1), s.count(0))
idx = s.count(1)
ans = min(ans,idx - s[:idx].count(1))
print(ans);

Submission status: Accepted

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

#Wを全部右に寄せる
sW = 0
sR = 0
fW = N
fR = N-1
res = 0

while True:
  for i in range(sW,N):
    if S[i]=="W":
      fW = i
      break
  for i in range(sR,N):
    if S[N-i-1]=="R":
      fR = i
      break
  if fW<N-fR-1:
    S[fW] = "R"
    S[N-fR-1] = "W"
    sW = fW
    sR = fR
    res += 1
  else:
    break
    
print(res)

Submission status: Accepted

Solution code:
from collections import deque

N = int(input())
C = deque(list(input()))

cnt = 0

while len(C) > 1:
    if C[0] == 'W' and C[-1] == 'R':
        cnt += 1
        C.popleft()
        C.pop()
    else:
        if C[0] == 'R':
            C.popleft()
        if C[-1] == 'W':
            C.pop()

print(cnt)

Submission status: Accepted

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

rcount = c.count("R")
WcountuntilR = c[0:rcount].count("W")
print(WcountuntilR)

Submission status: Accepted

Solution code:
N = int(input())
l = input()
k = [[0,0] for i in range(N)]
Rc = 0
Wc = 0
for i in range(N):
    if l[i]=='R':
        Rc += 1
    else:
        Wc += 1

for i in range(N-1):
    k[i+1][0]=k[i][0]
    if l[i]=='W':
        k[i+1][0]+=1
    k[i][1]=Rc+k[i+1][0]-(i+1)

ans = 3*10**5
for i in range(N):
    if ans >= max(k[i][0],k[i][1]):
        ans = max(k[i][0],k[i][1])


print(ans)

Submission status: Accepted

Solution code:
import sys
import  math
from heapq import *
import fractions
import bisect
stdin = sys.stdin
     
ns = lambda: stdin.readline().rstrip()
ni = lambda: int(stdin.readline().rstrip())
nm = lambda: map(int, stdin.readline().split())
nl = lambda: list(map(int, stdin.readline().split()))

N=int(input())
c=list(ns())
ans=0
w_l=[]
r_l=[]
for i in range(len(c)):
    if(c[i]=='W'):
        w_l.append(i)
    else:
        r_l.append(i)
    
w_l.sort()
r_l.sort(reverse=True)

for i in range(min(len(w_l),len(r_l))):
    if(w_l[i]<r_l[i]):
        ans+=1
    
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
A = input()
Ar = A[::-1]
i = 0
j = 0
res = 0
while True:
    x = A[i:-1].find("W")
    y = Ar[j:-1].find("R")
    if x == -1 or y == -1:
        break
    i += x
    j += y
    if i+j >= N:
        break
    else:
        res += 1
    i+= 1
    j+= 1
print(res)

Submission status: Accepted

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

from collections import deque

red = deque()
white = deque()
for i, ci in enumerate(c):
    if ci == "R":
        red.append(i)
    else:
        white.append(i)
if len(red) == 0:
    print(0)
    exit()
if len(white) == 0:
    print(0)
    exit()

red.appendleft(-1)
white.append(2000000)

cnt = 0
while True:
    r = red.pop()
    w = white.popleft()
    if w > r:
        print(cnt)
        break
    cnt += 1

Submission status: Accepted

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

Submission status: Accepted

Solution code:
def main():
    N = int(input())
    c = [x == 'R' for x in input().rstrip()]
    
    left = 0
    right = N - 1
    count = 0
    while left < right:
        while left < N and c[left] != False:
            left += 1
        while right >= 0 and c[right] != True:
            right -= 1
        if left < right:
            count += 1
            left += 1
            right -= 1
    print(count)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n = int(input())
c = input()
new_str_list = sorted(c)
C = ''.join(new_str_list)

count = 0
for i in range(n):
    if c[i] != C[i]:
        count += 1
print(count//2)

Submission status: Accepted

Solution code:
n = int(input())
C = list(input())
count_r = C.count("R")
count_r_right = C[:count_r].count("R")
print(min(count_r-count_r_right,C.count("W")))

Submission status: Accepted

Solution code:
N=int(input())
stones=list(input())
reds,whites=[0,0]
counter=0
for i in stones:
	if i=='R':
		reds+=1
	else:
		whites+=1
for i in range(N-whites,N):
	if stones[i]=='W':
		counter+=1
print(whites-counter)

Submission status: Accepted

Solution code:
n = int(input())
s = input()
w = []
r = []
for i,j in enumerate(s):
  if j == 'W':
    w.append(i)
  else:
    r.append(i)
if len(w) == 0 or len(r) == 0:
  print(0)
else:
  p = -1
  q = 0
  ans = 0
  mp = len(r)
  mq = len(w)
  while r[p] > w[q]:
    ans += 1
    p -= 1
    q += 1
    if q >= mq or -p > mp:
      break
  print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
from collections import Counter
def main():
    N = int(input())
    C = list(input().rstrip())
    D = Counter(C)
    E = D['R']
    CNT = 0
    for i in range(E):
        if C[i] == 'W':
            CNT += 1
    print(CNT)

if __name__ == '__main__':
    main()

Submission status: Accepted

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

count_r = c.count('R')
count = 0

for i in range(N):
	if count_r == 0: break
	if c[i] == 'W':
		count += 1
		count_r -= 1
	if c[i] == 'R':
		count_r -= 1

print(count)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import numpy as np

n = int(input())
s = np.array(list(map(lambda x: 1 if x == "W" else 0,
                      list(input()))), 
             dtype=int)

wp = np.cumsum(s)
ope = 0
alter = 0
for c, w in zip(s[::-1], wp[::-1]):
    # c == "W"
    if c == 1:
        continue

    # c == "R"
    if w - ope > 0:
        ope += 1
    
    if w - ope == 0:
        break

print(ope)

Submission status: Accepted

Solution code:
N = int(input())
C = list(map(str, input()))

W = N - C.count('W')
R = N - C.count('R')

CH = W - C[:W].count('R')
print(min(W, R, CH))

Submission status: Accepted

Solution code:
n = int(input())
s = input()
start = 0
end = n-1
count = [[0, 0] for _ in range(n)]
start_w = 0
end_r = 0
for i in range(n):
    count[i][0] = start_w
    if s[i] == "W":
        start_w += 1
for i in reversed(range(n)):
    count[i][1] = end_r
    if s[i] == "R":
        end_r += 1

print(min(map(max,count)))

Submission status: Accepted

Solution code:
n = int(input())
s = list(input())
j = 1
count = 0
for i in range(n):
    if s[i] == 'R':
        continue
    else:
        while 1:
            if j + i >= n:
                break
            elif s[-j] == 'R':
                s[i] = 'R'
                s[-j] = 'W'
                count += 1
                break
            j += 1
print(count)

Submission status: Accepted

Solution code:
n=int(input())
c=str(input())
r=0
w=0
for i in range (n):
    if c[i]=='R':
        r+=1
    else:
        w+=1
q=r
for j in range (r):
    if c[j]=='R':
        q-=1
print(q)

Submission status: Accepted

Solution code:
n = int(input())
c_l = list(input())
c_l = [ 1  if c == 'R' else 0 for c in c_l ]
r_n = sum(c_l)
w_n = sum(c_l[:r_n])
print(r_n-w_n)

Submission status: Accepted

Solution code:
from collections import deque

N = int(input())
c = list(input())
w_index = deque([i for i, x in enumerate(c) if x == 'W'])
r_index = deque([i for i, x in enumerate(c) if x == 'R'])

if len(w_index) == 0 or len(r_index) == 0:
    print(0)
    exit()

ans = 0

while w_index[0] < r_index[-1]:
    l = w_index.popleft()
    r = r_index.pop()
    w_index.append(r)
    r_index.appendleft(l)
    ans += 1
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
s=list(input())
i=0
j=n-1
ans=0
while i<j:
    while s[i]!="W" and i<j:
        i+=1
    while s[j]!="R" and i<j:
        j-=1
    if i<j:
        ans+=1
        i+=1
        j-=1
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
c = input()
numr = c.count("R")
a = "R"*numr + "W"*(n-numr)
ans = 0
for i in range(n):
  if c[i] != a[i]:
    ans += 1
print(ans//2)

Submission status: Accepted

Solution code:
N = int(input())
C = input()
ALL_R = "R" * len(C)
ALL_W = "W" * len(C)
RW = "R" * C.count("R") + "W" * C.count("W")
cnt1 = 0
cnt2 = 0
cnt3 = 0
for i in range(len(C)):
    if C[i] != ALL_R[i]:
        cnt1 += 1
    if C[i] != ALL_W[i]:
        cnt2 += 1
    if C[i] != RW[i]:
        cnt3 += 1
cnt3 //= 2
print(min(cnt1, cnt2, cnt3))

Submission status: Accepted

Solution code:
N = int(input())
l = list(input())
w = [0]*N
if l[0] == "W":
    w[0] = 1
for i in range(1,N):
    if l[i] == "W":
        w[i] = w[i-1] + 1
    else:
        w[i] = w[i-1]
kosuu = N - w[N-1]
if kosuu == 0:
    print(0)
    exit()
print(w[kosuu-1])

Submission status: Accepted

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

white_position = []
red_potition = []
for i in range(n):
    if li[i] == 'W':
        white_position.append(i)
    else:
        red_potition.append(i)
        
red_potition.sort(reverse=True)

cnt = 0
for s,t in zip(white_position, red_potition):
    if s < t:
        li[s] = 'R'
        li[t] = 'W'
        cnt += 1
        
check = False
for i in range(n):
    if li[i] == 'W':
        check = True
    if check == True and li[i] == 'R':
        cnt += 1

print(cnt)

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
import sys

def input(): return sys.stdin.readline().rstrip("\r\n")
def List(): return list(map(int, input().split()))
def Num(): return int(input())


n = Num()
s = input()
r, w = s.count('R'), s.count('W')
t = 'R' * r + 'W' * w
f, ss = 0, 0
for i in range(r):
    if t[i] != s[i]:
        f += 1
print(f)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
from collections import Counter
n = int(input())
c = list(input())
for i in range(n)[-1::-1]:
    if c[i] == "W":
        del c[i]
    else:
        break
c.reverse()
for i in range(len(c))[-1::-1]:
    if c[i] == "R":
        del c[i]
    else:
        break

d = Counter(c)
r = d["R"]
w = d["W"]
rc, wc = 0, 0
if w > r:
    c.reverse()
    for i in range(r):
        if c[i] == "R":
            rc += 1
    print(r - rc)
else:
    for i in range(w):
        if c[i] == "W":
            wc += 1
    print(w - wc)

Submission status: Accepted

Solution code:
from collections import deque
import bisect

N = int(input())

S = input()

Ws = deque([])
Rs = deque([])

for i in range(N):
  if S[i] == 'W':
    Ws.append(i)
  else:
    Rs.append(i)
    
cnt = 0
for i in range(len(Rs)-1,-1,-1):
  j = bisect.bisect_left(Ws, Rs[i])
  if j > 0:
    Ws.popleft()
    cnt += 1
    
print(cnt)

Submission status: Accepted

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

Submission status: Accepted

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

ans = 0

R = c.count('R')
W = c.count('W')
hoge = 'R' * R + 'W' * W

for i in range(N):
  if c[i] != hoge[i]:
    ans += 1

print(ans // 2)

Submission status: Accepted

Solution code:
n = int(input())
s = input()
nw = len(s.replace('R',''))
nr = n - nw

if (nr ==0) or (nw==0):
    print(0)
else:
    tmp_w = 0
    ret = n
    w_left = 0
    for i, c in enumerate(s):
        if c == 'W':
            w_left += 1
        r_right = nr + w_left - i - 1
        ret = min(ret, max(r_right, w_left))
    print(ret)

Submission status: Accepted

Solution code:
K = int(input())
C = input()
C = list(C)
r = C.count("R")
A = C[:r].count("W")
B = C[-K+r:].count("W")
# print(A)
# print(B)
cnt = 0
for _ in range(200000):
    if A > 0:
        if B > 0:
            A -= 1
            B += 1
            cnt += 1
        else:
            A -= 1
            cnt += 1
    else:
        break
print(cnt)

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
from itertools import accumulate, permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
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()
c = Counter(C)
R = c["R"] * "R" + c["W"] * "W"
# print(R)
r = c["R"]
w = c["W"]
# print(C[:r], C[r:])

a = Counter(C[:r])["W"] # make R
b = Counter(C[r:])["R"]

ans = min(max(a, b), r, w)
print(ans)

Submission status: Accepted

Solution code:
def main():
    input()  # n
    stones = input()
    white_counter = []
    white_stones = 0
    red_stones = 0
    for color in stones:
        if color == 'W':
            white_stones += 1
        else:
            red_stones += 1
        white_counter.append(white_stones)

    if red_stones == 0:
        print(0)
    else:
        print(white_counter[red_stones - 1])


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def readinput():
    n=int(input())
    c=list(input())
    return n,c

def findR(ir,c):
    i=ir
    while (i>=0 and c[i]=='W'):
        i-=1
    return i

def findW(iw,c):
    i=iw
    while(i<n and c[i]=='R'):
        i+=1
    return i

def main(n,c):
    iw=0
    iw=findW(iw,c)
    if iw==n:
        return 0
    ir=n-1
    ir=findR(ir,c)
    if ir==-1:
        return 0
    count=0
    while(iw<ir):
        #print(iw,ir)
        count+=1
        ir=findR(ir-1,c)
        iw=findW(iw+1,c)
    return count

if __name__=='__main__':
    n,c=readinput()
    ans=main(n,c)
    print(ans)

Submission status: Accepted

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

w_len=c.count("W")
r_len=len(c)-w_len

print(min(w_len,r_len,c[:r_len].count("W")))