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:
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
mod = 10 ** 9 + 7
mod1 = 998244353

# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

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

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

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

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


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


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


# -------------------game starts now----------------------------------------------------import math
class TreeNode:
    def __init__(self, k, v):
        self.key = k
        self.value = v
        self.left = None
        self.right = None
        self.parent = None
        self.height = 1
        self.num_left = 1
        self.num_total = 1


class AvlTree:

    def __init__(self):
        self._tree = None

    def add(self, k, v):
        if not self._tree:
            self._tree = TreeNode(k, v)
            return
        node = self._add(k, v)
        if node:
            self._rebalance(node)

    def _add(self, k, v):
        node = self._tree
        while node:
            if k < node.key:
                if node.left:
                    node = node.left
                else:
                    node.left = TreeNode(k, v)
                    node.left.parent = node
                    return node.left
            elif node.key < k:
                if node.right:
                    node = node.right
                else:
                    node.right = TreeNode(k, v)
                    node.right.parent = node
                    return node.right
            else:
                node.value = v
                return

    @staticmethod
    def get_height(x):
        return x.height if x else 0

    @staticmethod
    def get_num_total(x):
        return x.num_total if x else 0

    def _rebalance(self, node):

        n = node
        while n:
            lh = self.get_height(n.left)
            rh = self.get_height(n.right)
            n.height = max(lh, rh) + 1
            balance_factor = lh - rh
            n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
            n.num_left = 1 + self.get_num_total(n.left)

            if balance_factor > 1:
                if self.get_height(n.left.left) < self.get_height(n.left.right):
                    self._rotate_left(n.left)
                self._rotate_right(n)
            elif balance_factor < -1:
                if self.get_height(n.right.right) < self.get_height(n.right.left):
                    self._rotate_right(n.right)
                self._rotate_left(n)
            else:
                n = n.parent

    def _remove_one(self, node):
        """
        Side effect!!! Changes node. Node should have exactly one child
        """
        replacement = node.left or node.right
        if node.parent:
            if AvlTree._is_left(node):
                node.parent.left = replacement
            else:
                node.parent.right = replacement
            replacement.parent = node.parent
            node.parent = None
        else:
            self._tree = replacement
            replacement.parent = None
        node.left = None
        node.right = None
        node.parent = None
        self._rebalance(replacement)

    def _remove_leaf(self, node):
        if node.parent:
            if AvlTree._is_left(node):
                node.parent.left = None
            else:
                node.parent.right = None
            self._rebalance(node.parent)
        else:
            self._tree = None
        node.parent = None
        node.left = None
        node.right = None

    def remove(self, k):
        node = self._get_node(k)
        if not node:
            return
        if AvlTree._is_leaf(node):
            self._remove_leaf(node)
            return
        if node.left and node.right:
            nxt = AvlTree._get_next(node)
            node.key = nxt.key
            node.value = nxt.value
            if self._is_leaf(nxt):
                self._remove_leaf(nxt)
            else:
                self._remove_one(nxt)
            self._rebalance(node)
        else:
            self._remove_one(node)

    def get(self, k):
        node = self._get_node(k)
        return node.value if node else -1

    def _get_node(self, k):
        if not self._tree:
            return None
        node = self._tree
        while node:
            if k < node.key:
                node = node.left
            elif node.key < k:
                node = node.right
            else:
                return node
        return None

    def get_at(self, pos):
        x = pos + 1
        node = self._tree
        while node:
            if x < node.num_left:
                node = node.left
            elif node.num_left < x:
                x -= node.num_left
                node = node.right
            else:
                return (node.key, node.value)
        raise IndexError("Out of ranges")

    @staticmethod
    def _is_left(node):
        return node.parent.left and node.parent.left == node

    @staticmethod
    def _is_leaf(node):
        return node.left is None and node.right is None

    def _rotate_right(self, node):
        if not node.parent:
            self._tree = node.left
            node.left.parent = None
        elif AvlTree._is_left(node):
            node.parent.left = node.left
            node.left.parent = node.parent
        else:
            node.parent.right = node.left
            node.left.parent = node.parent
        bk = node.left.right
        node.left.right = node
        node.parent = node.left
        node.left = bk
        if bk:
            bk.parent = node
        node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
        node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
        node.num_left = 1 + self.get_num_total(node.left)

    def _rotate_left(self, node):
        if not node.parent:
            self._tree = node.right
            node.right.parent = None
        elif AvlTree._is_left(node):
            node.parent.left = node.right
            node.right.parent = node.parent
        else:
            node.parent.right = node.right
            node.right.parent = node.parent
        bk = node.right.left
        node.right.left = node
        node.parent = node.right
        node.right = bk
        if bk:
            bk.parent = node
        node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
        node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
        node.num_left = 1 + self.get_num_total(node.left)

    @staticmethod
    def _get_next(node):
        if not node.right:
            return node.parent
        n = node.right
        while n.left:
            n = n.left
        return n


# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
    def __init__(self, data, default='z', func=lambda a, b: min(a, b)):
        """initialize the segment tree with data"""
        self._default = default
        self._func = func
        self._len = len(data)
        self._size = _size = 1 << (self._len - 1).bit_length()

        self.data = [default] * (2 * _size)
        self.data[_size:_size + self._len] = data
        for i in reversed(range(_size)):
            self.data[i] = func(self.data[i + i], self.data[i + i + 1])

    def __delitem__(self, idx):
        self[idx] = self._default

    def __getitem__(self, idx):
        return self.data[idx + self._size]

    def __setitem__(self, idx, value):
        idx += self._size
        self.data[idx] = value
        idx >>= 1
        while idx:
            self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
            idx >>= 1

    def __len__(self):
        return self._len

    def query(self, start, stop):
        if start == stop:
            return self.__getitem__(start)
        stop += 1
        start += self._size
        stop += self._size

        res = self._default
        while start < stop:
            if start & 1:
                res = self._func(res, self.data[start])
                start += 1
            if stop & 1:
                stop -= 1
                res = self._func(res, self.data[stop])
            start >>= 1
            stop >>= 1
        return res

    def __repr__(self):
        return "SegmentTree({0})".format(self.data)


# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
    def __init__(self, data, default=0, func=lambda a, b: a + b):
        """initialize the segment tree with data"""
        self._default = default
        self._func = func
        self._len = len(data)
        self._size = _size = 1 << (self._len - 1).bit_length()

        self.data = [default] * (2 * _size)
        self.data[_size:_size + self._len] = data
        for i in reversed(range(_size)):
            self.data[i] = func(self.data[i + i], self.data[i + i + 1])

    def __delitem__(self, idx):
        self[idx] = self._default

    def __getitem__(self, idx):
        return self.data[idx + self._size]

    def __setitem__(self, idx, value):
        idx += self._size
        self.data[idx] = value
        idx >>= 1
        while idx:
            self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
            idx >>= 1

    def __len__(self):
        return self._len

    def query(self, start, stop):
        if start == stop:
            return self.__getitem__(start)
        stop += 1
        start += self._size
        stop += self._size

        res = self._default
        while start < stop:
            if start & 1:
                res = self._func(res, self.data[start])
                start += 1
            if stop & 1:
                stop -= 1
                res = self._func(res, self.data[stop])
            start >>= 1
            stop >>= 1
        return res

    def __repr__(self):
        return "SegmentTree({0})".format(self.data)


# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
    def __init__(self, MOD):
        self.MOD = MOD
        self.factorials = [1, 1]
        self.invModulos = [0, 1]
        self.invFactorial_ = [1, 1]

    def calc(self, n):
        if n <= -1:
            print("Invalid argument to calculate n!")
            print("n must be non-negative value. But the argument was " + str(n))
            exit()
        if n < len(self.factorials):
            return self.factorials[n]
        nextArr = [0] * (n + 1 - len(self.factorials))
        initialI = len(self.factorials)
        prev = self.factorials[-1]
        m = self.MOD
        for i in range(initialI, n + 1):
            prev = nextArr[i - initialI] = prev * i % m
        self.factorials += nextArr
        return self.factorials[n]

    def inv(self, n):
        if n <= -1:
            print("Invalid argument to calculate n^(-1)")
            print("n must be non-negative value. But the argument was " + str(n))
            exit()
        p = self.MOD
        pi = n % p
        if pi < len(self.invModulos):
            return self.invModulos[pi]
        nextArr = [0] * (n + 1 - len(self.invModulos))
        initialI = len(self.invModulos)
        for i in range(initialI, min(p, n + 1)):
            next = -self.invModulos[p % i] * (p // i) % p
            self.invModulos.append(next)
        return self.invModulos[pi]

    def invFactorial(self, n):
        if n <= -1:
            print("Invalid argument to calculate (n^(-1))!")
            print("n must be non-negative value. But the argument was " + str(n))
            exit()
        if n < len(self.invFactorial_):
            return self.invFactorial_[n]
        self.inv(n)  # To make sure already calculated n^-1
        nextArr = [0] * (n + 1 - len(self.invFactorial_))
        initialI = len(self.invFactorial_)
        prev = self.invFactorial_[-1]
        p = self.MOD
        for i in range(initialI, n + 1):
            prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
        self.invFactorial_ += nextArr
        return self.invFactorial_[n]


class Combination:
    def __init__(self, MOD):
        self.MOD = MOD
        self.factorial = Factorial(MOD)

    def ncr(self, n, k):
        if k < 0 or n < k:
            return 0
        k = min(k, n - k)
        f = self.factorial
        return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD


# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
    if a == 1 or n == 0:
        return 1
    if n % 2 == 0:
        s = powm(a, n // 2, m)
        return s * s % m
    else:
        return a * powm(a, n - 1, m) % m


# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
    zipped_pairs = zip(list2, list1)

    z = [x for _, x in sorted(zipped_pairs)]

    return z


# --------------------------------------------------product----------------------------------------
def product(l):
    por = 1
    for i in range(len(l)):
        por *= l[i]
    return por


# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
    left = 0
    right = n - 1

    count = 0

    while (left <= right):
        mid = int((right + left) / 2)

        # Check if middle element is
        # less than or equal to key
        if (arr[mid] < key):
            count = mid + 1
            left = mid + 1

        # If key is smaller, ignore right half
        else:
            right = mid - 1

    return count


# --------------------------------------------------binary----------------------------------------
def countdig(n):
    c = 0
    while (n > 0):
        n //= 10
        c += 1
    return c
def binary(x, length):
    y = bin(x)[2:]
    return y if len(y) >= length else "0" * (length - len(y)) + y

def countGreater(arr, n, k):
    l = 0
    r = n - 1

    # Stores the index of the left most element
    # from the array which is greater than k
    leftGreater = n

    # Finds number of elements greater than k
    while (l <= r):
        m = int(l + (r - l) / 2)
        if (arr[m] >= k):
            leftGreater = m
            r = m - 1

        # If mid element is less than
        # or equal to k update l
        else:
            l = m + 1

    # Return the count of elements
    # greater than k
    return (n - leftGreater)


# --------------------------------------------------binary------------------------------------
n=int(input())
e=str(input())
rc=e.count('R')
ans=0
cur=0
sr=0
for i in range(n):
    if e[i]=='R':
        sr+=1
        if cur<=rc-sr:
            continue
        else:
            ans+=1
    else:
        cur+=1
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
C = input()
S = [0]*(N+1)
for i in range(1, N+1):
    if C[i-1] == "R":
        S[i] = S[i-1]+1
    else:
        S[i] = S[i-1]

R_cnt = S[-1]
print(R_cnt - S[R_cnt])

Submission status: Accepted

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

Submission status: Accepted

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

ws = [i for i in range(N) if c[i] == 'W']
rs = [i for i in range(N) if c[i] == 'R']

if len(ws) == 0 or len(rs) == 0:
    print(0)
else:
    ans = 0
    while ws and rs and ws[0] < rs[-1]:
        del ws[0]
        del rs[-1]
        ans += 1
    print(ans)

Submission status: Accepted

Solution code:
N = int(input())
C = input()
R = C.count("R")
count = 0
for i in C[:R]:
  if i == "R":
    count += 1
print(R-count)

Submission status: Accepted

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

    l=0
    r=N-1
    ans = 0
    while l < r:
        while l < N and C[l] == 'R':
            l += 1
        while r >= 0 and C[r] == 'W':
            r -= 1
        
        if l < r:
            C[l] = 'R'
            C[r] = 'W'
            ans += 1
        # print(C, l, r)
        # return
    
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

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

r = N-1
w = 0

op = 0
while w < r : 
    while w < N and arr[w] != 'W' :
        w += 1
    while r >= 0 and arr[r] != 'R' :
        r -= 1

    if w < N and r >= 0 and w < r :
        op += 1
        arr[r], arr[w] = arr[w], arr[r]
        r -= 1
        w += 1  

print(op)

Submission status: Accepted

Solution code:
from math import ceil,floor,factorial,gcd,sqrt,log2,cos,sin,tan,acos,asin,atan,degrees,radians,pi,inf,comb
from itertools import accumulate,groupby,permutations,combinations,product,combinations_with_replacement
from collections import deque,defaultdict,Counter
from bisect import bisect_left,bisect_right
from operator import itemgetter
from heapq import heapify,heappop,heappush
from queue import Queue,LifoQueue,PriorityQueue
from copy import deepcopy
from time import time
from functools import reduce
import string
import sys
sys.setrecursionlimit(10 ** 7)
def input() : return sys.stdin.readline().strip()
def INT()   : return int(input())
def MAP()   : return map(int,input().split())
def LIST()  : return list(MAP())

n = INT()
c = list(input())
i = 0
j = n - 1
ans = 0
while i < j:
    while i < n and c[i] != 'W':
        i += 1
    while j > 0 and c[j] != 'R':
        j -= 1
    if i < j:
        ans += 1
        c[i] = 'R'
        c[j] = 'W'
print(ans)

Submission status: Accepted

Solution code:
N=int(input())
C=input()
from heapq import heappop,heappush
sr=[]
for i,c in enumerate(C):
    if c=='R':
        heappush(sr,-i)
r=C.count('R')
x=0
while sr and -sr[0]>=r:
    heappop(sr)
    x+=1
print(x)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N = int(input())
C = input()
l = 0
r = N-1
ans = 0
while l < r:
    while l < r and C[l] == 'R':
        l += 1
    while l < r and C[r] == 'W':
        r -= 1
    if l >= r:
        break
    ans += 1
    l += 1
    r -= 1
print(ans)

Submission status: Accepted

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

num = 0
x = N
flag = False
for i in range(N):
    if c[i] == "W":
        for j in reversed(range(x)):
            if j <= i:
                flag = True
                break
            elif c[j] == "R":
                c[i] = "R"
                c[j] = "W"
                x = j
                num += 1
                #print(i,j,c)
                break

    if flag:
        break

print(num)

Submission status: Accepted

Solution code:
N = int(input())
C = [c == "R" for c in input()]
count_red = C.count(True)
print(C[:count_red].count(False))

Submission status: Accepted

Solution code:
n = int(input())
cs = input()
nr = cs.count("R")
nw = cs.count("W")
cnt = 0
cnt1 = 0
for i in range(nr):
    if cs[i] == "W":
        cnt += 1
# for i in range(nr,n):
#     if cs[i] == "R":
#         cnt1 += 1

print(cnt)

Submission status: Accepted

Solution code:
# rr..wwにする
# 8
# W R W W R W R R
# R R R R W W W W
# 10
# WRRRRWRRWR
# -> 2
# 12
# WWRRRRWRWRRR
n = int(input())
c = list(input())
w_count = c.count("W")
if w_count == 0 or w_count == n:
    print(0)
    exit()
ans1 = 0
for i in range(n - 1, n - w_count - 1, -1):
    if c[i] == "R":
        ans1 += 1

# いっそ色を変える場合 必要なだけWかRにする
# ans2 = 0
# flag = False
# for i in range(n):
#     if c[i] == "W" and flag == False:
#         flag = True
#     elif c[i] == "W" and flag:
#         ans2 += 1
# print(ans1, ans2, w_count, n - w_count)
print(min(ans1, w_count, n - w_count))

Submission status: Accepted

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

c_r = c.count("R")

for i in range(c_r):
    if c[i] == "R":
        c_r -= 1

print(c_r)

Submission status: Accepted

Solution code:
N = int(input())
C = list(input())
RtoW = sum(map(lambda x: x=="R",C))
WtoR = 0
ans = RtoW
for i in range(N):
    if C[i] == "R":
        RtoW -= 1
    else:
        WtoR += 1
    ans = min(ans,max(RtoW,WtoR))

print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


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

    left = 0
    right = N - 1

    ans = 0
    while True:
        while left < N and C[left] == 'R':
            left += 1
        while right >= 0 and C[right] == 'W':
            right -= 1

        if left < right:
            ans += 1
            left += 1
            right -= 1
        else:
            break

    print(ans)
    return


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n = int(input())
s = list(input())
from collections import defaultdict
d=defaultdict(int)
for i in range(n):
    d[s[i]]+=1
ans=0
for x in s[:d['R']]:
    if x=='W':
        ans+=1
print(ans)

Submission status: Accepted

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

rcnt = c.count("R")
rstart = c[:rcnt].count("R")
print(rcnt - rstart)

Submission status: Accepted

Solution code:
n=int(input())
c=input()
if 'W' not in c or 'R' not in c:
  print(0)
  exit()
rr=[0]*(n+1)
lw=[0]*(n+1)
tmp=0
for i in range(n):
  x=c[i]
  if x=='W':
    tmp+=1
  lw[i+1]=tmp
tmp=0
for i in range(n-1,-1,-1):
  x=c[i]
  if x=='R':
    tmp+=1
  rr[i]=tmp
ans=n
for i in range(n+1):
  lwi=lw[i]
  rri=rr[i]
  tmp=lwi+rri-min(rri,lwi)
  ans=min(tmp,ans)
print(ans)
#print(lw)
#print(rr)

Submission status: Accepted

Solution code:


def submit():
    n = int(input())
    s = list(input())

    if "W" not in s or "R" not in s:
        print(0)
        return
        
    l = 0
    r = n - 1
    swap = 0
    while True:
        while s[l] != "W":
            l += 1
        while s[r] != "R":
            r -= 1
    
        if r < l:
            break
        s[l] = "R"
        s[r] = "W"
        swap += 1

    print(swap)

submit()

Submission status: Accepted

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

"""
RRRWWWになれば幸せ

8
WRWW RWRR
Csum = [0, 1, 1, 2, 3x, 3, 4, 4, 4]

"""

Csum = [0] * (N+1)
for i in range(N):
  Csum[i+1] = Csum[i] + (1 if C[i] == 'W' else 0)
  
# 赤白の個数
CW = Csum[N]
CR = N - CW

ans = 200001
# iを含む右を全部Wに、含まない左をRにする
for i in range(N+1):
  leftR = i - Csum[i]
  leftW = Csum[i]
  rightR = CR - leftR
  rightW = CW - leftW
  #print(i,leftR,leftW,rightR,rightW)
  cnt = 0
  # irekae
  cnt += min(leftW, rightR)
  leftW -= cnt
  leftR += cnt
  rightR -= cnt
  rightW += cnt
  cnt += leftW + rightR
  #print(cnt)
  ans = min(ans,cnt)
  
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
c=str(input())
c=list(c)
t1=[0]*n
t2=[0]*n
for i in range(len(c)):
  if c[i]=="R":
    t1[i]=1
  else:
    t2[i]=1
if sum(t1)==len(c) or sum(t2)==len(c):
  print(0)
else:
  ans=0
  t=sum(t1)
  for i in range(n):
    if t2[i]==1:
      ans=ans+1
      t=t-1
    if t1[i]==1:
      t=t-1
    if t==0:
      break
  print(ans)

Submission status: Accepted

Solution code:
q = int(input())
ans = 0
pala = input()
comp = "R"*pala.count("R")+"W"*pala.count("W")

for i in range(q):
    if pala[i] != comp[i]: ans += 1

print(ans//2)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub


import sys
# sys.setrecursionlimit(10**6)
# buff_readline = sys.stdin.buffer.readline
buff_readline = sys.stdin.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(buff_readline())


def read_int_n():
    return list(map(int, buff_readline().split()))


def read_float():
    return float(buff_readline())


def read_float_n():
    return list(map(float, buff_readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()

def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, C):
    ans = 0
    ri = []
    for i,c in enumerate(C):
        if c == 'R':
            ri.append(i)

    for i, c in enumerate(C):
        if c == 'W' and ri and ri[-1] > i:
            ans += 1
            ri.pop()

    return ans


def main():
    N = read_int()
    C = read_str()
    print(slv(N, C))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N=int(input())
c=input()
white=[]
red=[]
ans=0
for i in range(N):
    if c[i]=="W":
        white.append(i)
    else:
        red.append(i)
if len(white)==0 or len(red)==0:
    print(ans)
else:
    while len(white)!=0 and len(red)!=0:
        a=white.pop(0)
        b=red.pop()
        if a<b:
            ans+=1
        else:
            break
    print(ans)

Submission status: Accepted

Solution code:

def solve():
  N = int(input())
  C = input()  # 'RWRRW...'
  # WR is bad
  # 1. exchange two
  # 2. flip one
  # RRRRWWWWWW
  # max(R) < min(W)
  W = []
  R = []
  for i, c in enumerate(C):
    if c == 'W':
      W.append(i)
    else:
      R.append(i)
  if not W or not R:
    return 0
  #print(W, R)
  for i in range(min(len(W), len(R))):
    if R[-(1+i)] < W[i]:
      return i
  return min(len(W), len(R))
print(solve())

Submission status: Accepted

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

input()
C = input()

num_red = C.count('R')

ret = 0

for c in C[0:num_red]:
    if c == 'W': ret += 1

print(ret)

Submission status: Accepted

Solution code:
n = int(input())
s = list(input())
ans = 0
cnt_w = s.count("W")
j = 1
for i in range(n - cnt_w):
    if s[i] == "W":
        while s[-j] == "W":
            j += 1
        s[i] = "R"
        s[-j] = "W"
        ans += 1


print(ans)

Submission status: Accepted

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

rtow = string.count("R")
wtor = 0

anslist = [max(rtow, wtor)]
for c in string:
    if c == "W":
        wtor += 1
    else:
        # c == "R"
        rtow -= 1
    anslist.append(max(rtow, wtor))

print(min(anslist))

Submission status: Accepted

Solution code:
def main():
    n = int(input())
    s = input()
    ans = 0
    L, R = 0, n-1
    while L < R:
        if s[L] != "W":
            L += 1
        elif s[R] != "R":
            R -= 1
        else:
            ans += 1
            L += 1
            R -= 1
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
import math
import itertools
import bisect
from copy import copy
from collections import deque,Counter
from decimal import Decimal
def s(): return input()
def i(): return int(input())
def S(): return input().split()
def I(): return map(int,input().split())
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)
fact = math.factorial
sys.setrecursionlimit(10**9)
INF = 10**9
mod = 10**9+7

N = i()
c = s()
num = c.count('R')
print(c[:num].count('W'))

Submission status: Accepted

Solution code:
n=int(input())
c=input()
a=[]
for i in range(n):
    if(c[i]=='R'):
        a.append(0)
    else:
        a.append(1)

zero=0
one=0
for i in range(n):
    if(a[i]==0):
        zero+=1

ans=[zero]
for i in range(n):
    if(a[i]==0):
        zero-=1
    else:
        one+=1
    #print(zero,one)
    ans.append(max(zero,one))

print(min(ans))

Submission status: Accepted

Solution code:
inpl = lambda: list(map(int,input().split()))
N = int(input())
c = input()
ans = 0
i = 0
j = N-1
while True:
    while i < N and c[i] == 'R':
        i += 1
    while j >= 0 and c[j] == 'W':
        j -= 1
    if i > j:
        break
    else:
        ans += 1
        i += 1
        j -= 1
print(ans)

Submission status: Accepted

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

l = 0
r = N - 1
ans = 0
while True:
    while l < N and c[l] == 'R':
        l += 1
    while r >= 0 and c[r] == 'W':
        r -= 1
    if r < l:
        break
    c[r], c[l] = c[l], c[r]
    ans += 1

print(ans)