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: Time Limit Exceeded

Solution code:
import sys
import numpy as np

def a():
    N = int(input())
    c = list(str(input()))
    l = N-1
    s = 0

    if not ('W' in c) or not ('R' in c):
        print(0)
        return


    for i in range(int(N)):        
        if c[i] == 'W':
            for j in range(l,i,-1):
                if c[j] == 'R':
                    l = j-1
                    s = s+1
                    break
        if l < i:
            break
    print(s)
if __name__ == "__main__":
    a()

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
c = input()
cnt = 0
while 'WR' in c:
    cnt += 1
    w = c.find('W')
    r = c.rfind('R')
    c = list(c)
    c[w] = 'R'
    c[r] = 'W'
    c = ''.join(c)
print(cnt)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
C = list(input())
CC = C[::-1]
RC = C.count('W')
WC = C.count('R')
ans = min(WC, RC)
XC = 0
if ans==0:
    print(0)
else:
    while ans > XC:
        l = C.index('W')
        r = CC.index('R')
        if l > N-1-r:
            ans = min(XC, ans)
            break
        C[l],C[N-1-r] = C[N-1-r],C[l]
        CC[r],CC[N-l-1] = CC[N-l-1],CC[r]
        XC += 1
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
from math import ceil,sqrt,log,gcd
def ii():return int(input())
def si():return input().strip()
def mi():return map(int,input().split())
def li():return list(mi())
mod=1000000007

n=ii()
s=si()

    
l=0
r=n-1
ans=0
while(l<r):
    f=0
    for i in range(l,n):
        if s[i]=='W':
            l=i
            f=1
            break
    for i in range(r,-1,-1):
        if s[i]=='R':
            r=i
            break
    if(l>=r or f==0):
        break
    ans+=1
    l+=1
    r-=1

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
c = list(input())
sc = list(reversed(c))
ans = 0
r = 0
flg  = False

if 'W' not in set(c) or 'R' not in set(c):
    print(ans)


else:
    for i in range(n):
        if flg:
            break
        if c[i] == 'W':
            for j in range(r, n):
                r += 1
                if sc[j] == 'R':
                    if n >= i+j+2:
                        c[i] = 'R'
                        c[-1*j-1] = 'W'
                        ans += 1
                        sc = list(reversed(c))
                        break
                    else:
                        flg = True
                        break

                
            

    print(ans)

Submission status: Time Limit Exceeded

Solution code:
from math import ceil,sqrt,log,gcd
def ii():return int(input())
def si():return input().strip()
def mi():return map(int,input().split())
def li():return list(mi())
mod=1000000007

n=ii()
s=si()

    
l=0
r=n-1
ans=0
while(l<r):
    f=0
    for i in range(l,n):
        if s[i]=='W':
            l=i
            f=1
            break
    for i in range(r,-1,-1):
        if s[i]=='R':
            r=i
            break
    if(l>r or f==0):
        break
    ans+=1
    l+=1
    r-=1

print(ans)

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
data=list(input())
if "W" not in data or "R" not in data:
    print(0)
else:
    s=0
    while True:
        first_w_index=data.index("W")
        data2=list(reversed(data))
        final_r_index=N-1-data2.index("R")
        if first_w_index < final_r_index:
            data[first_w_index]="R"
            data[final_r_index]="W"
            s += 1
        else:
            print(s)
            break

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np

def a():
    N = int(input())
    c = tuple(str(input()))
    l = N-1
    s = 0
    for i in range(int(N)):        
        if c[i] == 'W':
            for j in range(l,i,-1):
                if c[j] == 'R':
                    l = j-1
                    s = s+1
                    break
        if l < i:
            break
    print(s)
if __name__ == "__main__":
    a()

Submission status: Time Limit Exceeded

Solution code:
import sys

def II(): return int(input())
def MI(): return map(int,input().split())
def LI(): return list(map(int,input().split()))
def TI(): return tuple(map(int,input().split()))
def RN(N): return [input().strip() for i in range(N)]


def main():
    N = II()
    c = str(input())

    x = 1
    ans = 0
    y = 0

    for i in range(N):
        if y != 0:
            break
        if c[i] == "W":
            for j in range(x, N):
                ii = -j
                if c[ii] == "R" and j < N-i:
                    ans += 1
                    x = j+1
                    break
                if x>= N-i:
                    y += 1
                    break



    print(ans)

if __name__ == "__main__":
	main()

Submission status: Time Limit Exceeded

Solution code:
import math
N= int(input())
c=list(str(input()))
#N=4
#c=['W', 'W', 'R', 'R']
#c.reverse()
#print(c)


num=0
for i in reversed(range(N)):
    if c[i]=='R' :
        for u in (range(i)):
            if c[u]=='W':
                c[u]='y'
                c[i]='W'
                num+=1
                break
            
#print(c)
print(num)

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
c=input()
ans=0
#WRがなくなるまでの最小繰り返し数
#Rの左はR.右はなんでもOK（RR?）
#Wの右はW.左はなんでもOK(?WW)
"""
RRRRRR
WWWWWW
RWWWWWW
RRRRRRRW
の大よそ4パターンが存在する
全部やって小さいのでいい？
２か所の色が変わっていいことなんてあるのか？？？

WRWWRWRR
を３回操作で変更する方法
左にRを集め、右にWを集めきればいい
前から順にみていき処置をするか、全部見たうえで計算式を立てるか（多分公社）
Wが連続、Rが連続、RWならOK（カウントを戻す）
WとRの個数をカウントする
#半分より右側にあるWの個数、半分より左側にあるRの個数で、少ないほうがまず＋
#残りは塗り替える
#一番真ん中はWならOK、Rなら＋１
"""
#最小の分割店を見つける
if len(set(list(c)))==1:
    ans=0
    print(ans)
else:
    #最小の分割店を見つける
    ans=100000000000000000
    for i in range(N):
        W=c[:i].count("W")#変更すべきWの数
        R=c[i:].count("R")
        if max(R,W)<ans:
            ans=max(R,W)
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np

def a():
    N = int(input())
    c = list(str(input()))
    l = N-1
    s = 0
    for i in range(int(N)):        
        if c[i] == 'W':
            for j in range(l,i,-1):
                if c[j] == 'R':
                    l = j-1
                    s = s+1
                    break
        if l < i:
            break
    print(s)
if __name__ == "__main__":
    a()

Submission status: Time Limit Exceeded

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

W = S.find("W")
R = S.rfind("R")
if W ==-1 or R ==-1:
  print(0)
  exit()
for i in range(10**7):
  W = S.find("W")
  R = S.rfind("R")
  if S[W:R+1].find("WR") == -1:
    print(i)
    break
  S = S[:W]+"R"+S[W+1:R]+"W"+S[R+1:]

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
C = list(input())
CC = C[::-1]
RC = C.count('W')
WC = C.count('R')
MC = min(WC, RC)
XC = 0
if MC==0:
    print(0)
else:
    while True:
        l = C.index('W')
        r = CC.index('R')
        if l > N-1-r:
            print(min(XC, MC))
            break
        C[l],C[N-1-r] = C[N-1-r],C[l]
        CC[r],CC[N-l-1] = CC[N-l-1],CC[r]
        XC += 1
        if MC<=XC:
            print(MC)
            break

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
import sys 

readline = sys.stdin.readline

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

if (not 'W' in C) or (not 'R' in C):
    print(0)
    sys.exit()

counter = 0
for i in range(N):
    w_index = C.index('W')
    r_index = C.rindex('R')
    counter += 1

    if w_index > r_index:
        break

    # 石の入れ替え
    C_list = list(C)
    C_list[w_index] = 'R'
    C_list[r_index] = 'W'
    C = ''.join(C_list)

print(counter - 1)

Submission status: Time Limit Exceeded

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


# print(s.find('WR'))
# print(s.rfind('WR'))

ope = 0

while(1) :
	if s.find('WR') == -1 and s.rfind('WR') == -1 :
		break
	elif s.find('WR') != s.rfind('WR') :
		sl = list(s)
		sl[s.find('WR')] = 'R'
		sl[s.rfind('WR') + 1] = 'W'
		s = "".join(sl)
	else :
		sl = list(s)
		sl[s.find('W')] = 'R'
		sl[s.rfind('R')] = 'W'
		s = "".join(sl)
	ope += 1


print(ope)

Submission status: Time Limit Exceeded

Solution code:
WHITE = 0
RED = 1
_ = input()
C = input()
s = []
for c in C:
  if c == "W":
    s.append(WHITE)
  else:
    s.append(RED)
    
def helper(s):
  if len(s) <= 1:
    return 0
  if s[0] == WHITE and s[-1] == RED:
    return 1 + helper(s[1:-1])
  if s[0] == RED:
    return helper(s[1:])
  if s[-1] == WHITE:
    return helper(s[:-1])

print(helper(s))

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = list(input())
# A = list("RRRWWRR")
# import numpy as np
# A = np.array(A)
W = set()
R = set()
for i,a in enumerate(A):
    if a=="W":W.add(i)
    else:R.add(i)
# W = set(np.where(A=="W")[0])
# R = set(np.where(A=="R")[0])
n = 0
# print(W,R)
if (W!=set())&(R!=set()):
    while (min(W)<max(R)):
        w,r = min(W),max(R)
        W.remove(w)
        R.remove(r)
        W.add(r)
        R.add(w)
        # A[w],A[r] = A[r],A[w]
        n +=1
        # print(W,R)
        # if n == len(A):break
    # print(A)
    print(n)
else:print(0)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
c = list(input())
import numpy as np
count = 0
while len(c) > 0:
    for i in range(len(c)):
        if c[i] == "W":
            c = c[i:]
            break
    for i in range(len(c)-1):
        i = i+1
        if c[-i] == "R":
            c = c[:len(c)-i+1]
            break
    #print(len(c))
    if c[0] == "R" or c[-1] == "W":
        break
    for i in range(len(c)):
        i = i+1
        if c[-i] == "R":
            c = c[1:-1]
            #print(c)
            count += 1
            break
print(count)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
c = input()
c = list(c)
f = 0
ans = 0
while f == 0:
  if 'R' in c and 'W' in c:
    r = len(c) - c[::-1].index('R') - 1
    w = c.index('W')
    c[r] = 'W'
    c[w] = 'R'
    ans += 1
    for i, e in enumerate(c):
      if e == 'R':
        c[i] = ''
      else:
        c.remove('')
        break
  else:
    f = 1
    break
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
C = input()
C = C.lstrip('R').rstrip('W')

ans = 0
for _ in range(10**5):
    if len(C) > 0:
        l = C.find('R')
        r = C[::-1].find('W')
        n = min(l, r)
        C = C[n:-n]
        C = C.lstrip('R').rstrip('W')
        ans += n
    else:
        break
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
c = input()
cnt = 0
for i in range(n):
    r = c[i:].rfind('R') + i
    if c[i] == 'W' and i < r and r != -1:
        l = list(c)
        l[i] = 'R'
        l[r] = 'W'
        cnt += 1
        c = ''.join(l)

print(cnt)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
C = list(input())
CC = C[::-1]
RC = C.count('W')
WC = C.count('R')
MC = min(WC, RC)
XC = 0
if MC==0:
    print(0)
else:
    while True:
        l = C.index('W')
        r = CC.index('R')
        if l > N-1-r:
            print(min(XC, MC))
            break
        C[l],C[N-1-r] = C[N-1-r],C[l]
        CC[r],CC[N-l-1] = CC[N-l-1],CC[r]
        XC += 1

Submission status: Time Limit Exceeded

Solution code:

def change(stones):

    whiteind = stones.find('W')
    redind = stones.rfind('R')

    if whiteind == -1:
        return 'end'

    if whiteind > redind:
        return 'end'

    wklist = list(stones)
    wklist[whiteind] = 'R'
    wklist[redind] = 'W'

    return ''.join(wklist)


def main():
    N = int(input())
    stones = input()

    count = 0
    for i in range(N//2):
        stones = change(stones)
        if stones == 'end':
            break
        count += 1


    print(count)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

C = C.lstrip('R')

count = 0
while True:

    try:
        base_index = C[::-1].index('RW')
        target_index = C.index('W')
        base_index = len(C) - base_index - 1

        C = C[:target_index] + 'R' + C[target_index+1:base_index] + 'W' + C[base_index+1:]
        count += 1
    except ValueError:
        break

print(count)

Submission status: Time Limit Exceeded

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

import sys
sys.setrecursionlimit(200000)


def solve(stones, count):
    if 'WR' not in stones:
        return count

    index_R = stones.rindex('R')
    index_W = stones.index('W')

    # 「もっとも右にあるR」と「もっとも左にあるW」を交換する
    new_stones = (stones[:index_W] + 'R' + stones[index_W + 1:index_R] + 'W' +
                  stones[index_R + 1:])

    count += 1
    return solve(new_stones, count)


if __name__ == "__main__":
    N = int(input())
    stones = input()

    count = 0

    result = solve(stones, count)
    print(result)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
c = input()
ans = 0
for _ in range(N):
    fs = 0
    ls = len(c)
    for i, ci in enumerate(c):
        fs = i
        if ci == 'W':
            break
    for i , ci in enumerate(c[::-1]):
        if i + fs >= N:
            break
        ls -= 1
        if ci == 'R':
            break
    if fs == ls:
        break
    ans += 1
    c = c[fs + 1:ls]
    #print(c)
    if len(c) <= 1:
        break
print(ans)

Submission status: Time Limit Exceeded

Solution code:
def getIndex(l, x, default=-1):
    return l.index(x) if x in l else default

def getLastIndex(l, x, default=-1):
    l = list(reversed(l))
    return len(l) - l.index(x) - 1 if x in l else default

N = int(input())
c = list(input())
ans = 0
while(True):
    indexW = getIndex(c, 'W')
    indexR = getLastIndex(c, 'R')
    if indexR < indexW or indexW == -1 or indexR == -1:
        break
    c[indexW] = 'R'
    c[indexR] = 'W'
    ans += 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys

def II(): return int(input())
def MI(): return map(int,input().split())
def LI(): return list(map(int,input().split()))
def TI(): return tuple(map(int,input().split()))
def RN(N): return [input().strip() for i in range(N)]


def main():
    N = II()
    c = str(input())

    numW = c.count("W")
    x = 1
    ans = 0
    y = 0

    for i in range(N):
        if y != 0:
            break
        if c[i] == "W":
            for j in range(x, N):
                ii = -j
                if c[ii] == "R" and j < N-i:
                    ans += 1
                    x = j+1
                    #print(i)
                    break
                if x>= N-1:
                    y += 1
                    break



    print(ans)

if __name__ == "__main__":
	main()

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
altar=input()
stones=list(altar)
count=0

def condn(stones):
    new=""
    for x in stones:
        new+=x
    if ('WR' in new):
        return True
    else:
        return False
        
while(condn(stones)):
    i1=stones.index('W')
    i2=len(stones) -1- stones[::-1].index('R')
    stones[i1],stones[i2]=stones[i2],stones[i1]
    count+=1
print (count)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
cs = input()
import re

def search(cs):
    todo = []
    for i, c in enumerate(cs):
        if c=="R":
            if (i-1)!=-1:
                if cs[i-1] =="W":
                    todo.append(i)
    return todo

def replace(sentence, num, word):
    return sentence[:num]+word+sentence[num+1:]

todo = search(cs)
if len(todo)==0:
    print(0)
else:
    count = 0
    while len(todo)!=0:
        arg = todo[-1]
        tmp = cs[:arg]
        m = re.match(r".*W.*", tmp)
        if not m is None:
            tmp = replace(tmp, m.start(), "R")
            tmp += cs[arg:]
            tmp = replace(tmp, arg, "W")
            renew_todo = search(tmp)
        else:
            tmp = cs
            renew_todo = todo
        if len(renew_todo)<len(todo):
            count+=1
            todo = renew_todo
            cs = tmp
        else:
            count+=1
            cs = replace(cs, arg, "W")
            todo = search(cs)
    print(count)

Submission status: Time Limit Exceeded

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

W = S.find("W")
R = S.rfind("R")
if W ==-1 or R ==-1:
  print(0)
  exit()
for i in range(10**7):
  W = S.find("W")
  R = S.rfind("R")
  if S[W:R+1].find("WR") == -1:
    print(i)
    break
  S = S[:W]+"R"+S[W+1:R]+"W"+S[R+1:]

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
data=list(input())
if "W" not in data or "R" not in data:
    print(0)
else:
    s=0
    while True:
        final_r_index=N
        first_w_index=data.index("W")
        for i in reversed(range(final_r_index)):
            if data[i] == "R":
                final_r_index=i
                break
        if first_w_index < final_r_index:
            data[first_w_index]="R"
            data[final_r_index]="W"
            s += 1
        else:
            print(s)
            break

Submission status: Time Limit Exceeded

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

c=[i for i in s]
reverse_c = c[::-1]
#print(c)
#print(reverse_c)

R_count=c.count("R")
if R_count == 0 or R_count == N:
    print(0)
    exit()

flg=0
ans=0
while flg == 0:
    for i in range(N):
        left_W=c.index("W")#１番左の白のindex
        right_R=N-1-reverse_c.index("R")#１番右の赤のindex
        #print(left_W)
        #print(right_R)
        #入れ替え処理
        c[left_W]="R"
        c[right_R]="W"
        #print(c)

        cnt=0
        for j in range(R_count):
            if c[j] == "R":
                cnt+=1
            else:
                break
        ans+=1
        if cnt == R_count:
            print(ans)
            exit()

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = list(input())
# A = list("RRRRR")
import numpy as np
A = np.array(A)
W = set(np.where(A=="W")[0])
R = set(np.where(A=="R")[0])
n = 0
# print(W,R)
if (W!=set())&(R!=set()):
    while (min(W)<max(R)):
        w,r = min(W),max(R)
        W.remove(w)
        R.remove(r)
        W.add(r)
        R.add(w)
        # A[w],A[r] = A[r],A[w]
        n +=1
        # print(W,R)
        # if n == len(A):break
    # print(A)
    print(n)
else:print(0)

Submission status: Time Limit Exceeded

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

C = [s for s in STR]
cnt_w = C.count('W')    # 最大入替回数

ans = 0
for i in range(cnt_w):
    idx = C.index('W')
    if idx < cnt_w:
        C[i] = 'R'
        target = STR.rfind('R')
        if target < idx:
            break
        del C[target]
        ans += 1
        STR = ''.join(C)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np
N = int(input())
c = np.array(list(str(input())))
l = N-1
s = 0
for i in range(int(N)):        
    if c[i] == 'W':
        for j in range(l,i,-1):
            if c[j] == 'R':
                l = j-1
                s = s+1
                break
    if l < i:
        break
print(s)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
c = list(input())
mn = 100000
ls = []
for i in range(n) :
    left = c[:i+1]
    right = c[i+1:]
    ls.append(max(left.count("W"), right.count("R")))
for i in range(n) :
    mn = min(ls[i], mn)
print(mn)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
c = input()
l = list(c)
ans = 0
a = 0
b = n
while c.count("WR") > 0 :
   for i in range(a,b) :
       if l[i] == "W" :
           l[i] = "R"
           a = i
           break
   for j in reversed(range(a,b)) :
       if l[j] == "R" :
           l[j] = "W"
           b = j
           break
   c = ''.join(l)
   ans += 1
print(ans)

Submission status: Time Limit Exceeded

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

import sys
import numpy as np
int1 = lambda x: int(x) - 1
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(500000)

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

w_idx = []
r_idx = []
for i, c in enumerate(C):
    if c == 'W':
        w_idx.append(i)
    else:
        r_idx.append(i)

if (len(w_idx) == 0) | (len(r_idx) == 0):
    print(0)
    sys.exit()

cnt = 0

while w_idx[0] < r_idx[-1]:

    w_acc = w_idx.pop(0)
    r_acc = r_idx.pop(-1)
    w_idx.append(r_acc)
    r_idx.append(w_acc)
    w_idx.sort()
    r_idx.sort()
    cnt += 1

print(cnt)

Submission status: Time Limit Exceeded

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

ans = 0

s = c.count('WR')

while s > 0:
    a = c.find('W')
    b = c.rfind('R')
    c = c[:a]+'R'+c[a+1:]
    c = c[:b]+'W'+c[b+1:]
    ans = ans + 1
    s = c.count('WR')

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
c = input()
l =list(c)
L = len(l)//2
ans = 0
k = n-1

for i in range(k):
    for j in range(k,i,-1):
        if l[i]== 'W' and l[j] == 'R':
            l[j] = 'W'
            ans += 1
            k = j-1
            break
print(ans)

Submission status: Time Limit Exceeded

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

def cut(c):
    num = 0
    for i in range(N):
        if c[i]!='R':
            break
        else:
            num+=1
    return c[num:]

c = cut(c)
cnt = 0

def change(c):
    flag = False
    num=0
    for i, n in enumerate(c[::-1]):
        if n=='R':
            num = i
            flag = True
            break
    return c[1:len(c)-1-num]+'W'+c[len(c)-num:], flag
    
while True:
    c, flag = change(c)
    if not flag:
        break
    c = cut(c)
    cnt +=1
print(cnt)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
st = input()
from collections import deque,Counter
st = deque(st)
cnt = Counter(st)
ans = 0
while len(st) > 1:
    if st[0] == 'W' and st[-1] == 'R':
        ans += 1
        st.popleft()
        st.pop()
        cnt['R']-=1
        cnt['W']-=1
    elif st[0] =='R' and st[-1] == 'R':
        st.popleft()
        cnt['R']-=1
    elif st[0] == 'R' and st[-1] == 'W':
        st.popleft()
        st.pop()
        cnt['R']-=1
        cnt['W']-=1
    elif cnt['R']==0:
            break
    else:
        ans += 1
        cnt['R']-=1
        cnt['W']-=2
        st = list(st)
        st.pop([i for i, x in enumerate(st) if x == 'R'][-1])
        st = deque(st)
        st.popleft()
        st.pop()
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from queue import deque
def main():
    R, W = "R", "W"
    N = int(input())
    _C = input()
    C = deque(_C)

    count = 0
    while True:
        i = len(C) -1
        while C[i] != R:
            i -= 1
            if i < 0:
                break
        j = 0
        while C[j] != W:
            j +=1
            if j >= len(C):
                break
        if  i < j:
            break
        C[i], C[j] = C[j], C[i]
        count += 1
    
    print(count)
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

if not "W" in c or not "R" in c :
        print(0)
        exit()

w =  c.index("W")
c = c[w:]
# print(c)

for i in range(1000000000):
    if not "R" in c :
        print(i)
        exit()
    cr = c[:]
    cr.reverse()
    w =  c.index("W")
    r = cr.index("R")
    
    c[-(r+1)] = "W"
    c.pop(w)
    # print(c)
    # print(w,r)
    if w > len(c)-r:
        print(i)
        exit()

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter
import copy 
n=int(input())
c=input()
cl=copy.deepcopy(c)
cl=list(cl)
d=Counter(c)
ans=0


if d["R"]==0 or d["W"]==0:
  print(0)
  exit()
swap=0
if d["R"]>=n//2:
  r=n//2
else:
  r=d["R"]
  
for i in range(r):
  indexes = [j for j, x in enumerate(cl) if x == "R"]
  #print(cl)
  if cl[i]=="W":
    cl[indexes[-1]]="W"
    cl[i]="R"
    swap+=1

#print(cl)
#print(cl[cl.index("W"):])
#print(swap)
d=Counter(cl[cl.index("W"):])
ans+=swap+d["R"]
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
c = list(input())
Wcount = c.count('R')
CursedCount = 0
i = 0
while i < N-1:
    if c[i] == 'W':
        if c[i+1] == 'R':
            t = N-1
            while i < t:
                if c[t] == 'R':
                    c[i] = 'R'
                    c[t] = 'W'

                    CursedCount += 1
                    i = -1
                    break
                t-=1
    i += 1


print(min(Wcount,CursedCount))

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
n = int(input())
t = input()
*c, = map(int, t.replace(*"W1").replace(*"R0"))

"""
1100 -> 0101 -> 0011
00
10110100 -> 00111100 -> 00011110 -> 00001111
"""

a = 0
i, j = 0, 1
while i + j < n:
    if c[i] == 1 and c[-j] == 0:
        a += 1
        i += 1
        j += 1
    elif c[i] == c[-j] == 0:
        i += 1
    elif c[i] == c[-j] == 1:
        j += 1
print(a)

Submission status: Time Limit Exceeded

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

n = int(input())
cs = input()

c_sliced = cs[0:cs.rfind('R') + 1]
c_list = list(c_sliced)

def replace(s_list):
    string = ''.join(s_list)
    index_r = string.rfind('R')
    index_w = string.find('W')
    s_list[index_r] = 'W'
    s_list[index_w] = 'R'
    return ''.join(s_list)

i = 0
while c_sliced.rfind('R') > c_sliced.find('W') and c_sliced.rfind('R') * c_sliced.find('W') >= 0:
    i += 1
    c_list = list(c_sliced)
    c_sliced = replace(c_list)

print(i)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
c = input()
l = list(c)
ans = 0
a = 0
b = n
while c.count("WR") > 0 :
   for i in range(a,b) :
       if l[i] == "W" :
           l[i] = "R"
           a = i
           break
   for j in reversed(range(0,b)) :
       if l[j] == "R" :
           l[j] = "W"
           b = j
           break
   c = ''.join(l)
   ans += 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
c = input()
l =list(c)
L = len(l)//2
ans = 0
k = n-1

for i in range(n-1):
    for j in range(k,i,-1):
        if l[i]== 'W' and l[j] == 'R':
            l[j] = 'W'
            ans += 1
            k = j-1
            break
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
list=list(input())
count=0
list_red=[i for i, x in enumerate(list) if x == "R"]
list_white=[i for i, x in enumerate(list) if x == "W"]
if len(list_white)!=0  and len(list_red)!=0:
    max_c=max(list_red)
    min_c=min(list_white)
while len(list_white)!=0  and len(list_red)!=0 and max_c>=min_c:
    list_red.remove(max_c)
    list_white.remove(min_c)
    if len(list_white)==0  or len(list_red)==0:
        count+=1
        break
    max_c=max(list_red)
    min_c=min(list_white)
    count+=1
print(count)

Submission status: Time Limit Exceeded

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

done = False
count = 0

for i in range(N):
    if done:
        break
    if c[i] == "R":
        continue
    else:
        l = c[i + 1 :]
        for j in reversed(range(len(l))):
            if l[j] == "R":
                c[i] = "R"
                c[i + 1 + j] = "W"
                count += 1
                break

print(count)

Submission status: Time Limit Exceeded

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

import sys
sys.setrecursionlimit(200000)


def count_WR(stones):
    return stones.count('WR')


def solve(stones, count):
    if count_WR(stones) == 0:
        return count

    index_R = stones.rindex('R')
    index_W = stones.index('W')

    # 「もっとも右にあるR」と「もっとも左にあるW」を交換する
    new_stones = (stones[:index_W] + 'R' + stones[index_W + 1:index_R] + 'W' +
                  stones[index_R + 1:])

    count += 1
    return solve(new_stones, count)


if __name__ == "__main__":
    N = int(input())
    stones = input()

    count = 0

    result = solve(stones, count)
    print(result)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
cs = input()
import re

def search(cs):
    tmp = []
    todo = []
    for i, c in enumerate(cs):
        if c=="R":
            tmp.append(0)
            if (i-1)!=-1:
                if tmp[i-1]:
                    todo.append(i)
        else:
            tmp.append(1)
    return todo

def replace(sentence, num, word):
    return sentence[:num]+word+sentence[num+1:]

todo = search(cs)
if len(todo)==0:
    print(0)
else:
    count = 0
    while len(todo)!=0:
        arg = todo[-1]
        tmp = cs[:arg]
        m = re.match(r".*W.*", tmp)
        if not m is None:
            tmp = replace(tmp, m.start(), "R")
            tmp += cs[arg:]
            tmp = replace(tmp, arg, "W")
            renew_todo = search(tmp)
        else:
            tmp = cs
            renew_todo = todo
        if len(renew_todo)<len(todo):
            count+=1
            todo = renew_todo
            cs = tmp
        else:
            count+=1
            cs = replace(cs, arg, "W")
            todo = search(cs)
    print(count)

Submission status: Time Limit Exceeded

Solution code:
def change(stones):

    whiteind = stones.find('W')
    redind = stones.rfind('R')

    if whiteind == -1:
        return 'end'

    if whiteind > redind:
        return 'end'

    wklist = list(stones)
    wklist[whiteind] = 'R'
    wklist[redind] = 'W'

    return ''.join(wklist)


def main():
    N = int(input())
    stones = input()

    count = 0
    while(count < (N/2)):
        stones = change(stones)
        if stones == 'end':
            break
        count += 1


    print(count)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def resolve():
    N = int(input())
    c = input()
    # RRRRWWWWみたいな形にすれば良い
    # 色の塗替えよりも色の交換の方が2つの石を動かせるので良いはず
    # 一番右のRと一番左のWを入れ替え続けるのが最善手
    for i in range(N):
        if "WR" not in c:
            print(i)
            break
        red_index = c.rfind("R")
        white_index = c.find("W")
        c = c[:white_index] + "R" + c[white_index+1:red_index] + "W"

resolve()

Submission status: Time Limit Exceeded

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

def cut(c):
    num = 0
    for i in range(N):
        if c[i]!='R':
            break
        else:
            num+=1
    return c[num:]

c = cut(c)
cnt = 0

def change(c):
    nu = 0
    for i, n in enumerate(c[::-1]):
        if n=='R':
            num = i
            break
    return c[1:len(c)-1-num]+'W'+c[len(c)-num:]
    
while 'R' in c:
    c = change(c)
    c = cut(c)
    cnt +=1
print(cnt)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
c = list(input())
mn = 100000
cnt_lw = []
cnt_rr = []
for i in range(n) :
    left = c[:i+1]
    right = c[i+1:]
    cnt_lw.append(left.count("W"))
    cnt_rr.append(right.count("R"))
for i in range(n) :
    mn = min(max(cnt_lw[i],cnt_rr[i]), mn)
print(mn)