Problem:


Score : 500 points

Problem Statement

Snuke, who loves animals, built a zoo.

There are N animals in this zoo. They are conveniently numbered 1 through N, and arranged in a circle.
The animal numbered i (2≤i≤N-1) is adjacent to the animals numbered i-1 and i+1. Also, the animal numbered 1 is adjacent to the animals numbered 2 and N, and the animal numbered N is adjacent to the animals numbered N-1 and 1.

There are two kinds of animals in this zoo: honest sheep that only speak the truth, and lying wolves that only tell lies.

Snuke cannot tell the difference between these two species, and asked each animal the following question: "Are your neighbors of the same species?" The animal numbered i answered s_i. Here, if s_i is o, the animal said that the two neighboring animals are of the same species, and if s_i is x, the animal said that the two neighboring animals are of different species.

More formally, a sheep answered o if the two neighboring animals are both sheep or both wolves, and answered x otherwise.
Similarly, a wolf answered x if the two neighboring animals are both sheep or both wolves, and answered o otherwise.

Snuke is wondering whether there is a valid assignment of species to the animals that is consistent with these responses. If there is such an assignment, show one such assignment. Otherwise, print -1.

Constraints

3 ≤ N ≤ 10^{5}

s is a string of length N consisting of o and x.

Input

The input is given from Standard Input in the following format:

N
s

Output

If there does not exist an valid assignment that is consistent with s, print -1.
Otherwise, print an string t in the following format. The output is considered correct if the assignment described by t is consistent with s.

t is a string of length N consisting of S and W.

If t_i is S, it indicates that the animal numbered i is a sheep. If t_i is W, it indicates that the animal numbered i is a wolf.

Sample Input 1

6
ooxoox

Sample Output 1

SSSWWS

For example, if the animals numbered 1, 2, 3, 4, 5 and 6 are respectively a sheep, sheep, sheep, wolf, wolf, and sheep, it is consistent with their responses. Besides, there is another valid assignment of species: a wolf, sheep, wolf, sheep, wolf and wolf.

Let us remind you: if the neiboring animals are of the same species, a sheep answers o and a wolf answers x. If the neiboring animals are of different species, a sheep answers x and a wolf answers o.

Sample Input 2

3
oox

Sample Output 2

-1

Print -1 if there is no valid assignment of species.

Sample Input 3

10
oxooxoxoox

Sample Output 3

SSWWSSSWWS



Sample input:
6
ooxoox


Sample output:
SSSWWS

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, gcd
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from heapq import heappush, heappop
from functools import reduce, lru_cache
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 TUPLE(): return tuple(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 
#mod = 998244353
from decimal import *
#import numpy as np
#decimal.getcontext().prec = 10

N = INT()
s = input()

def is_ok(x, idx):
	if s[idx] == "o":
		if x[idx] == "S" and x[idx-1] == x[idx+1]:
			return True
		elif x[idx] == "W" and x[idx-1] != x[idx+1]:
			return True
		else:
			return False
	elif s[idx] == "x":
		if x[idx] == "S" and x[idx-1] != x[idx+1]:
			return True
		elif x[idx] == "W" and x[idx-1] == x[idx+1]:
			return True
		else:
			return False

start = list(product(["S", "W"], repeat=2))

for i in range(4):
	ws = []
	ws.extend(start[i])
	for j in range(1, N-1):
		if ws[j] == "S":
			if s[j] == "o":
				ws.append(ws[j-1])
			else:
				if ws[j-1] == "S":
					ws.append("W")
				else:
					ws.append("S")
		elif ws[j] == "W":
			if s[j] == "x":
				ws.append(ws[j-1])
			else:
				if ws[j-1] == "S":
					ws.append("W")
				else:
					ws.append("S")
	if is_ok(ws, -1) and is_ok(ws, 0):
		print(*ws, sep="")
		break

else:
	print(-1)

Submission status: Accepted

Solution code:
from itertools import product
N=int(input())
s=input()
s = s+s

ans = None
for s0, s1 in product(range(2), repeat=2):#0:wolf, 1:sheep
    tmp = [s0, s1]
    for i in range(1, N):
        if (tmp[i] == 0 and s[i] == "o") or (tmp[i] == 1 and s[i] == "x"):
            if tmp[i-1] == 0:
                tmp.append(1)
            else:
                tmp.append(0)
        else:
            if tmp[i-1] == 0:
                tmp.append(0)
            else:
                tmp.append(1)
    if s0 == tmp[-1]:
        if (s0 == 0 and s[0] == "o") or (s0 == 1 and s[0] == "x"):
            if s1 == tmp[-2]:
                continue
        else:
            if s1 != tmp[-2]:
                continue
        ans = tmp 
        break

if ans is None:
    print(-1)
else:
    ans = ans[:-1]
    final = ""
    for a in ans:
        if a == 0:
            final += "W"
        else:
            final += "S"
    print(final)

Submission status: Accepted

Solution code:
N = int(input())
S = input()
from collections import deque
T = [deque([0, 0]),
     deque([0, 1]),
     deque([1, 0]),
     deque([1, 1])]
for s in S:
    for t in T:
        l = len(t)
        if (s == 'o') ^ t[l-1]:
            t.append(t[l-2])
        else:
            t.append(t[l-2]^1)

ans = '-1'
wrap = lambda x:'{' + str(x) + '}'
for t in T:
    if t[0] == t[N] and t[1] == t[N+1]:
        t.pop(); t.popleft()
        ans = ''.join(wrap(i) for i in t).format('S','W')
        break
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
s = list(input())
rev = {"S":"W","W":"S"}

ok = False
for x,y in [("S","S"),("S","W"),("W","S"),("W","W")]:
    ans = [x,y]+["a"]*(N-2)

    for i in range(1,N-1):
        if ans[i]=="S" and s[i]=="o":
            ans[i+1]=ans[i-1]
        elif ans[i]=="S" and s[i]=="x":
            ans[i+1]=rev[ans[i-1]]
        elif ans[i]=="W" and s[i]=="o":
            ans[i+1]=rev[ans[i-1]]
        elif ans[i]=="W" and s[i]=="x":
            ans[i+1]=ans[i-1]

    if ans[N-1]==ans[1] and ((s[0]=="o" and ans[0]=="S") or (s[0]=="x" and ans[0]=="W")):
        ok = True
    if ans[N-1]!=ans[1] and ((s[0]=="x" and ans[0]=="S") or (s[0]=="o" and ans[0]=="W")):
        ok = True

    if not ok:
        continue
    
    ok=False
    if ans[N-2]==ans[0] and ((s[N-1]=="o" and ans[N-1]=="S") or (s[N-1]=="x" and ans[N-1]=="W")):
        ok = True
    if ans[N-2]!=ans[0] and ((s[N-1]=="x" and ans[N-1]=="S") or (s[N-1]=="o" and ans[N-1]=="W")):
        ok = True

    if ok:
        break

if ok:
    print("".join(ans))
else:
    print(-1)

Submission status: Accepted

Solution code:
d = {"WWo": "S",
     "WSo": "W",
     "SWo": "W",
     "SSo": "S",
     "WWx": "W",
     "WSx": "S",
     "SWx": "S",
     "SSx": "W",
    }

combo = ["SS","SW","WS","WW"]

N = int(input())
z = input()

matched = False
txt = []
for c in combo:
  keep = c[0]
  left = c
  txt = []
  for i in range(N):
    txt.append(left[1])
    new_ch = d[left+z[i]]
    left = left[1] + new_ch
  if left == c:
    matched = True
    break

if matched:
  print(*txt,sep="")
else:
  print("-1")

Submission status: Accepted

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

# 0番目、1番目を決め打つ（４通り）ことで、連鎖的に次の種類を決めることができる
# 1番の証言通りに2番を決める, ..., N-1番目の証言通りに0番目を決める
# 最初に決めた0番目の種類と、最終的に導かれた0番目の種類が異なる場合、実現不可能
# 実現が可能な場合、0番目の証言が未検証なので検証する必要がある

# True:=羊, False:=狼　とする
# True/Falseで書くことで、not演算子での反転が使えて少し楽になる
for ptn in [[True, True], [True, False], [False, True], [False, False]]:
    # 1,2,...N-1番目の証言から2,3,...,N-1,0番目の種類を決める
    for i in range(1, n):
        if ptn[i] == True and s[i] == "o":
            ptn.append(ptn[i - 1])
        elif ptn[i] == True and s[i] == "x":
            ptn.append(not ptn[i - 1])
        elif ptn[i] == False and s[i] == "o":
            ptn.append(not ptn[i - 1])
        elif ptn[i] == False and s[i] == "x":
            ptn.append(ptn[i - 1])

    # 最初に決めた0番目の種類と、最終的に導かれた0番目の種類が等しい場合
    # 0番目の証言を検証する
    if ptn[0] == ptn[-1]:
        # 0番目に相当するものが重複しているので末尾の方を除いておく
        ptn.pop(-1)
        flag = False

        if ptn[0] == True and s[0] == "o":
            if ptn[-1] == ptn[1]:
                flag = True
        if ptn[0] == True and s[0] == "x":
            if ptn[-1] != ptn[1]:
                flag = True
        if ptn[0] == False and s[0] == "o":
            if ptn[-1] != ptn[1]:
                flag = True
        if ptn[0] == False and s[0] == "x":
            if ptn[-1] == ptn[1]:
                flag = True

        # 検証の結果、0番目の証言が矛盾しなかった場合、実現可能
        if flag == True:
            ans = []
            for i in range(n):
                if ptn[i] == True:
                    ans.append("S")
                elif ptn[i] == False:
                    ans.append("W")

            print("".join(ans))
            exit()

# 矛盾しないものが見つからなかった場合
print(-1)

Submission status: Accepted

Solution code:
n=int(input())
s=input()
ans1="SS"
ans2="SW"
ans3="WS"
ans4="WW"

def check(ans):
    for i in range(1,n-1):
        if s[i]=="o"  and ans[i]=="S":
            ans+=ans[i-1]
        elif s[i]=="o" and ans[i]=="W":
            if ans[i-1]=="W":
                ans+="S"
            else:
                ans+="W"
         
        elif s[i]=="x"  and ans[i]=="S":
            if ans[i-1]=="W":
                ans+="S"
            else:
                ans+="W"
        elif s[i]=="x" and  ans[i]=="W":
            ans+=ans[i-1]
    flg=False
    if s[n-1]=="o":
        if ans[n-1]=="S":
            if ans[0]==ans[n-2]:
                flg=True
    if s[n-1]=="o":
        if ans[n-1]=="W":
            if ans[0]!=ans[n-2]:
                flg=True
    if s[n-1]=="x":
        if ans[n-1]=="S":
            if ans[0]!=ans[n-2]:
                flg=True
    if s[n-1]=="x":
        if ans[n-1]=="W":
            if ans[0]==ans[n-2]:
                flg=True
    if flg:
        if s[0]=="o":
            if ans[0]=="S":
                if ans[1]==ans[n-1]:
                    print(ans)
                    exit()
        if s[0]=="o":
            if ans[0]=="W":
                if ans[1]!=ans[n-1]:
                    print(ans)
                    exit()
        if s[0]=="x":
            if ans[0]=="S":
                if ans[1]!=ans[n-1]:
                    print(ans)
                    exit()
        if s[0]=="x":
            if ans[0]=="W":
                if ans[1]==ans[n-1]:
                    print(ans)
                    exit()
check(ans1)
check(ans2)
check(ans3)
check(ans4)
print(-1)

Submission status: Accepted

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

# ls[i]とls[i-1]の情報からls[i+1]を決定する関数
def decide_right(ls):
    '''
    ls[0]とls[1]が確定したlsを与えられたら、その情報からls全体(一意に定まる)を返す
    '''
    N = len(ls)
    for i in range(1,N-1):
        if ls[i] == 'S':
            if s[i] == 'o':
                ls[i+1] = ls[i-1]
            else:
                if ls[i-1] == 'S':
                    ls[i+1] = 'W'
                else:
                    ls[i+1] = 'S'
        else:
            if s[i] == 'o':
                if ls[i-1] == 'S':
                    ls[i+1] = 'W'
                else:
                    ls[i+1] = 'S'
            else:
                ls[i+1] = ls[i-1]
    return ls

'''
def decide_left(ls):
    #ls[1]とls[0]が確定したlsを与えられたら、その情報からls全体(一意に定まる)を返す
    
    N = len(ls)
    for i in range(N,0,-1):
        if s[i] == 'o':
            ls[i-1] = ls[i+1]
        else:
            if ls[i+1] == 'S':
                ls[i-1] = 'W'
            else:
                ls[i-1] = 'S'
'''

def check(first):
    # 矛盾のないlsを発見し次第それをreturn、可能性が無くなったらFalseをリターン
    # ls1は左から決めていく
    ls1 = [0] * (n+1)
    ls1[0] = first

    for second in ['S','W']:
        ls1[1] = second
        ls1 = decide_right(ls1)
        
        if ls1[0] != ls1[-1]:
            continue
        
        # 0の両隣の判定

        ls = ls1[:-1]
        res = True
        for i in range(n):
            r = i+1
            if r == n:
                r = 0
            if ls[i] == 'S':
                if s[i] == 'o' and ls[i-1] != ls[r]:
                    res = False
                    break
                elif s[i] == 'x' and ls[i-1] == ls[r]:
                    res = False
                    break
            else:
                if s[i] == 'o' and ls[i-1] == ls[r]:
                    res = False
                    break
                elif s[i] == 'x' and ls[i-1] != ls[r]:
                    res = False
                    break
        if not res:
            continue
        '''
        ls2 = [0] * (n+1)
        ls2[-1] = first
        if s[0] == 'o':
            ls2[-2] = second
        else:
            if second == 'S':
                ls2[-2] = 'W'
            else:
                ls2[-2] = 'S'
        ls2 = decide_left(ls2)
        if ls2[0] != ls2[-1]:
            continue
        
        for i in range(n+1):
            if ls1[i] != ls2[i]:
                continue
        '''
        
        return ls1[:-1]
    
    return False

for first in ['S','W']:
    c = check(first)
    if c:
        print(*c,sep='')
        sys.exit()
print(-1)

Submission status: Accepted

Solution code:
n = int(input())
s = input()
a = ["SS", "SW", "WS", "WW"]
for i in a:
    ans = i
    for j in range(n - 2):
        if ans[j + 1] == "S":
            if s[j + 1] == "o":
                if ans[j] == "S":
                    ans += "S"
                else:
                    ans += "W"
            else:
                if ans[j] == "S":
                    ans += "W"
                else:
                    ans += "S"
        else:
            if s[j + 1] == "o":
                if ans[j] == "S":
                    ans += "W"
                else:
                    ans += "S"
            else:
                if ans[j] == "S":
                    ans += "S"
                else:
                    ans += "W"
    flag = True
    if ans[n - 1] == "S":
        if s[n - 1] == "o":
            if ans[n - 2] != ans[0]:
                flag = False
        else:
            if ans[n - 2] == ans[0]:
                flag = False
    else:
        if s[n - 1] == "o":
            if ans[n - 2] == ans[0]:
                flag = False
        else:
            if ans[n - 2] != ans[0]:
                flag = False
    if ans[0] == "S":
        if s[0] == "o":
            if ans[n - 1] != ans[1]:
                flag = False
        else:
            if ans[n - 1] == ans[1]:
                flag = False
    else:
        if s[0] == "o":
            if ans[n - 1] == ans[1]:
                flag = False
        else:
            if ans[n - 1] != ans[1]:
                flag = False
    if flag == True:
        print(ans)
        break
    else:
        continue
else:
    print(-1)

Submission status: Accepted

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

start = ["SS", "SW", "WS", "WW"]

for st in start:
    ans = st
    for i in range(1, n):
        if s[i] == "o" and ans[i] == "S":
            if ans[i-1] == "S":
                ans += "S"
            else:
                ans += "W"
        elif s[i] == "x" and ans[i] == "S":
            if ans[i-1] == "S":
                ans += "W"
            else:
                ans += "S"
        elif s[i] == "o" and ans[i] == "W":
            if ans[i-1] == "S":
                ans += "W"
            else:
                ans += "S"
        elif s[i] == "x" and ans[i] == "W":
            if ans[i-1] == "S":
                ans += "S"
            else:
                ans += "W"

    if ans[0] == ans[-1]:
        ans = ans[:n]
        ok = False
        if s[0] == "o" and ans[0] == "S":
            if ans[-1] == ans[1]:
                ok = True
        elif s[0] == "x" and ans[0] == "S":
            if ans[-1] != ans[1]:
                ok = True
        elif s[0] == "o" and ans[0] == "W":
            if ans[-1] != ans[1]:
                ok = True
        elif s[0] == "x" and ans[0] == "W":
            if ans[-1] == ans[1]:
                ok = True
        if ok:
            print(ans[:n])
            exit()
print(-1)

Submission status: Accepted

Solution code:
N = int(input())
S = input()
a = ["SS","SW","WS","WW"]

for i in range(N):
  for j in range(4):
    a[j]+="SW"[::-1 if S[i]=="o" else 1][a[j][i]==a[j][i+1]]

for i in range(4):
  if a[i][1]==a[i][N+1] and a[i][0]==a[i][N]:
    print(a[i][1:N+1])
    break
else:
  print(-1)

Submission status: Accepted

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

# S:1 W:-1
T = [[1, 1], [1, -1], [-1, 1], [-1, -1]]
for t in T:
    for i in range(n-1):
        if t[i+1] == 1:
            if s[i+1] == "o":
                t.append(t[i])
            else:
                t.append(-1*t[i])
        else:
            if s[i+1] == "o":
                t.append(-1*t[i])
            else:
                t.append(t[i])
#print(T)
for t in T:
    if t[0] == t[-1]:
        if t[0] == 1:
            if s[0] == "o" and t[-2] == t[1]:
                ans = t
                break
            elif s[0] == "x" and t[-2] != t[1]:
                ans = t
                break
        elif t[0] == -1:
            if s[0] == "o" and t[-2] != t[1]:
                ans = t
                break
            elif s[0] == "x" and t[-2] == t[1]:
                ans = t
                break
else:
    print(-1)
    exit()


str_ans = ""
for i in range(n):
    if ans[i] == 1:
        str_ans += "S"
    elif ans[i] == -1:
        str_ans += "W"
print(str_ans)

Submission status: Accepted

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

# 一匹目、二匹目について4通り試す
# 羊:True, 狼:False
from itertools import product
for tf in product([True, False], repeat=2):
    tf = list(tf)
    for i in range(1, n):
        if s[i] == 'o':
            if tf[i]:
                tf.append(tf[i-1])
            else:
                tf.append(not tf[i-1])
        else:
            if tf[i]:
                tf.append(not tf[i-1])
            else:
                tf.append(tf[i-1])

    if tf[0] == tf[-1]:
        tf.pop(-1)
        flag = False
        if s[0] == 'o':
            if tf[0]:
                if tf[-1] == tf[1]:
                    flag = True
            else:
                if tf[-1] != tf[1]:
                    flag = True
        else:
            if tf[0]:
                if tf[-1] != tf[1]:
                    flag = True
            else:
                if tf[-1] == tf[1]:
                    flag = True

        if flag:
            for i in range(n):
                if tf[i]:
                    tf[i] = 'S'
                else:
                    tf[i] = 'W'
            print(''.join(tf))
            exit()

print(-1)

Submission status: Accepted

Solution code:
import sys
def input(): return sys.stdin.readline().strip()

def main():
    N = int(input())
    S = input()
    """
    0, 1番目を決定すればそこから先は一意に確定するのでO(4N)で愚直にチェック可能
    """
    ans = [0] * N
    for i in range(4):
        ans[0] = i % 2
        ans[1] = i // 2
        for j in range(1, N - 1):
            if S[j] == 'o' and ans[j] == 1:
                ans[j + 1] = ans[j - 1]
            elif S[j] == 'o' and ans[j] == 0:
                ans[j + 1] = 1 - ans[j - 1]
            elif S[j] == 'x' and ans[j] == 1:
                ans[j + 1] = 1 - ans[j - 1]
            else:
                ans[j + 1] = ans[j - 1]
        if S[-1] == 'o' and ans[-1] == 1 and ans[-2] != ans[0]: continue
        if S[-1] == 'o' and ans[-1] == 0 and ans[-2] == ans[0]: continue
        if S[-1] == 'x' and ans[-1] == 1 and ans[-2] == ans[0]: continue
        if S[-1] == 'x' and ans[-1] == 0 and ans[-2] != ans[0]: continue
        if S[0] == 'o' and ans[0] == 1 and ans[-1] != ans[1]: continue
        if S[0] == 'o' and ans[0] == 0 and ans[-1] == ans[1]: continue
        if S[0] == 'x' and ans[0] == 1 and ans[-1] == ans[1]: continue
        if S[0] == 'x' and ans[0] == 0 and ans[-1] != ans[1]: continue
        t = ''
        for a in ans: 
            if a == 0:
                t += 'W'
            else:
                t += 'S'
        print(t)
        return
    print(-1)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import math,itertools,fractions,heapq,collections,bisect,sys,queue,copy

sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7
dd=[(-1,0),(0,1),(1,0),(0,-1)]
ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
# def LF(): return [float(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return input()

def main():
  N=I()
  s=S()
  a=['S','W']
  aa=(['S','S'],['S','W'],['W','S'],['W','W'])

  for ans in aa:
    for i in range(1,N-1):
      if ans[i]=='S':
        if s[i]=='o':
          ans.append(ans[i-1])
        else:
          ind=a.index(ans[i-1])
          ans.append(a[1-ind])
      else:
        if s[i]=='o':
          ind=a.index(ans[i-1])
          ans.append(a[1-ind])
        else:
          ans.append(ans[i-1])
    stress=''.join(str(x) for x in ans)
    f=True
    for i in range(N):
      if stress[i]=='S':
        if i==0:
          if s[i]=='o':
            if not (stress[-1]==stress[i+1]):
              # return 'aaa1'+' '+stress
              f=False
          else:
            if not (stress[-1]!=stress[i+1]):
              # return 'aaa2'
              f=False
        elif i==N-1:
          if s[i]=='o':
            if not (stress[i-1]==stress[0]):
              # return 'aaa3'
              f=False
          else:
            if not (stress[i-1]!=stress[0]):
              # return 'aaa4'
              f=False
        else:
          if s[i]=='o':
            if not (stress[i-1]==stress[i+1]):
              # return 'aaa5'
              f=False
          else:
            if not (stress[i-1]!=stress[i+1]):
              # return 'aaa6'
              f=False
      else:
        if i==0:
          if s[i]=='o':
            if not (stress[-1]!=stress[i+1]):
              # return 'bbb1'
              f=False
          else:
            if not (stress[-1]==stress[i+1]):
              # return 'bbb2'
              f=False
        elif i==N-1:
          if s[i]=='o':
            if not (stress[i-1]!=stress[0]):
              # return 'bbb3'
              f=False
          else:
            if not (stress[i-1]==stress[0]):
              # return 'bbb4'
              f=False
        else:
          if s[i]=='o':
            if not (stress[i-1]!=stress[i+1]):
              # return 'bbb5'
              f=False
          else:
            if not (stress[i-1]==stress[i+1]):
              # return 'bbb6'
              f=False

    if f:
      return ''.join(str(x) for x in ans)

  return -1

# main()
print(main())

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys 
from collections import defaultdict
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
N = int(readline())
S = readline().decode()

st = ['SS','SW','WS','WW']

# 8通りの分岐を辞書に登録
d = defaultdict(int)
d['SSo'] = 'S'
d['SSx'] = 'W'
d['SWo'] = 'W'
d['SWx'] = 'S'
d['WSo'] = 'W'
d['WSx'] = 'S'
d['WWo'] = 'S'
d['WWx'] = 'W'
 

#答えの候補をansに代入
ans = []
for s in st:
    t = s  
    for i in range(1,N-1):
        tmp = t[-2:]
        ss = tmp + S[i]
        t += d[ss]
    ans.append(t)

# 答えの候補が矛盾しないかのチェック
for a in ans:
    b = a[N-2]+a[N-1]+S[N-1]
    if d[b] != a[0]:
        continue
    b = a[N-1]+a[0]+S[0]
    if d[b] != a[1]:
        continue
    print(a)
    sys.exit()

print(-1)

Submission status: Accepted

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

init = ["SS", "SW", "WS", "WW"]
next_animal = { ("S","o","S"):"S",
                ("S","o","W"):"W",
                ("S","x","S"):"W",
                ("S","x","W"):"S",
                ("W","o","S"):"W",
                ("W","o","W"):"S",
                ("W","x","S"):"S",
                ("W","x","W"):"W"}
for X in init:
    SW = X
    for i in range(1,N):
        SW += next_animal[SW[i],s[i],SW[i-1]]
    ls = len(SW)
    if SW[0] == SW[ls-1] and next_animal[SW[0],s[0],SW[ls-2]] == SW[1]:
        print(SW[:ls-1])
        break
else:
    print(-1)

Submission status: Accepted

Solution code:
def check(before, center, after, saying):
    return ([center, saying] in [["S", "o"], ["W", "x"]] and before == after)\
           or ([center, saying] in [["S", "x"], ["W", "o"]] and before != after)


def main():
    n = int(input())
    s = list(input())
    ans = "-1"
    for init in ["S", "W"]:
        if ans != "-1":
            break
        for next in ["S", "W"]:
            now_ans = ["" for _ in range(n)]
            now_ans[0] = init
            now_ans[1] = next
            for i in range(1, n - 1):
                if [now_ans[i], s[i]] in [["S", "o"], ["W", "x"]]:
                    now_ans[i + 1] = now_ans[i - 1]
                else:
                    now_ans[i + 1] = "W" if now_ans[i - 1] == "S" else "S"
            if check(now_ans[-2], now_ans[-1], now_ans[0], s[-1]) and check(now_ans[-1], now_ans[0], now_ans[1], s[0]):
                ans = "".join(now_ans)
                break
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

def f(SW,ox,prev):
  if SW=='S':
    if ox == 'o':
      if prev=='S': return 'S'
      else: return 'W'
    else:
      if prev=='S': return 'W'
      else: return 'S'
  else:
    if ox == 'o':
      if prev=='S': return 'W'
      else: return 'S'
    else:
      if prev=='S': return 'S'
      else: return 'W'

combination=[('S','S'),('S','W'),('W','S'),('W','W')]
ok=0
for j in range(4):
  if ok==1:break
  ans=[]
  for i in range(N):
    if i == 0:
      first,last = combination[j]
      ans.append(first)
      now = first
      next_ = f(now,S[i],last)
      continue
    if i == N-1:
      if last == next_ and first==f(next_,S[i],ans[-1]):
        ok=1
        ans.append(next_)
        break
      else:break
    ans.append(next_)
    next_ = f(next_,S[i],ans[-2])
    
if ok==1:
  print(''.join(ans))
else:
  print(-1)

Submission status: Accepted

Solution code:
import sys
N = int(input())
s = input()
not_sw = {'S':'W', 'W':'S'}

for sw1 in ['S', 'W']:
    for sw2 in ['S', 'W']:
        flag = True
        ans = [''] * (N+1)
        ans[0] = sw1
        ans[-1] = sw1
        if (s[0] == 'o' and ans[0] == 'S')  or (s[0] == 'x' and ans[0] == 'W'):
            ans[1] = sw2
            ans[-2] = sw2
        elif (s[0] == 'x' and ans[0] == 'S')  or (s[0] == 'o' and ans[0] == 'W'):
            ans[1] = not_sw[sw2]
            ans[-2] = sw2
        for i in range(1, N-2):
            if (s[i] == 'o' and ans[i] == 'S')  or (s[i] == 'x' and ans[i] == 'W'):
                ans[i+1] = ans[i-1]
            elif (s[i] == 'x' and ans[i] == 'S')  or (s[i] == 'o' and ans[i] == 'W'):
                ans[i+1] = not_sw[ans[i-1]]
        for i in range(N-2, N):
            if (s[i] == 'o' and ans[i] == 'S')  or (s[i] == 'x' and ans[i] == 'W'):
                if ans[i+1] != ans[i-1]:
                    flag = False
            elif (s[i] == 'x' and ans[i] == 'S')  or (s[i] == 'o' and ans[i] == 'W'):
                if ans[i+1] != not_sw[ans[i-1]]:
                    flag = False
        if flag:
            print(''.join(ans[:-1]))
            sys.exit()
print(-1)

Submission status: Accepted

Solution code:
def abc055_d():
    n = int(input())
    s = str(input())
    ss = s[-1] + s + s[0]

    def solve(ini1, ini0):
        res = [None] * (n+2)
        res[1] = ini1
        res[0] = ini0
        for i in range(1, n+1):
            if ss[i] == 'o':
                if res[i] == 'S' and res[i-1] == 'S': res[i+1] = 'S'
                if res[i] == 'S' and res[i-1] == 'W': res[i+1] = 'W'
                if res[i] == 'W' and res[i-1] == 'S': res[i+1] = 'W'
                if res[i] == 'W' and res[i-1] == 'W': res[i+1] = 'S'
            else:
                if res[i] == 'S' and res[i-1] == 'S': res[i+1] = 'W'
                if res[i] == 'S' and res[i-1] == 'W': res[i+1] = 'S'
                if res[i] == 'W' and res[i-1] == 'S': res[i+1] = 'S'
                if res[i] == 'W' and res[i-1] == 'W': res[i+1] = 'W'
        return res

    ans = '-1'
    ini = [('S','S'), ('S','W'), ('W','S'), ('W','W')]
    for ini1, ini0 in ini:
        res = solve(ini1, ini0)
        if res[0] == res[n] and res[1] == res[n+1]:
            ans = ''.join(res[1:n+1])
            break
    print(ans)

if __name__ == '__main__':
    abc055_d()