我在嘗試不要每次碰到E就要重來 但是數字總是有一些落差from sys import stdindef main():s=stdin.readline()[1:].replace("\n","").replace("L","TL").replace("E","TE").split("T")i=0stack=[1,0]l=-1ans=0while iif s[i][0]=="L":stack.append([int(s[i][1:]),i])elif s[i]=="E":stack[-1][0]-=1if(stack[-1][0]>0):i=stack[-1][1]else:stack.pop()elif l!=-1:ans+=abs(int(s[i])-l)l=int(s[i])else:l=int(s[i])i+=1print(ans)main()
strg = input()
lis = []
num = 0
for i in range(len(strg)):
s = strg[i]
if s=="T": lis.append(s)
elif s=="L": lis.append(s)
elif s=="E": lis.append(s)
else:
num *= 10
num += int(s)
if i+1==len(strg) or (strg[i+1]=="T" or strg[i+1]=="L" or strg[i+1]=="E"):
lis.append(num)
num = 0
ans = 0
index = 0
tp = 10
def loop(num,ix):
global lis,index,tp,ans
index = ix
while lis[index] != "E":
n = lis[index]
index += 1
if n == "T": continue
elif n == "L": loop(int(lis[index]),index+1)
else:
ans += abs(n-tp)
tp = n
if num!=1:
loop(num-1,ix)
else:
index +=1
return
def scan():
global lis,ans,index,tp
while index != len(lis):
s = lis[index]
index+=1
if s == "T": continue
elif s == "L": loop(int(lis[index]),index+1)
else:
ans += abs(s-tp)
tp = s
scan()
print(ans)
我用遞迴解
也是40%
我在嘗試不要每次碰到E就要重來 但是數字總是有一些落差from sys import stdindef main():s=stdin.readline()[1:].replace("\n","").replace("L","TL").replace("E","TE").split("T")i=0stack=[1,0]l=-1ans=0while iif s[i][0]=="L":stack.append([int(s[i][1:]),i])elif s[i]=="E":stack[-1][0]-=1if(stack[-1][0]>0):i=stack[-1][1]else:stack.pop()elif l!=-1:ans+=abs(int(s[i])-l)l=int(s[i])else:l=int(s[i])i+=1print(ans)main()
strg = input()
lis = []
num = 0
for i in range(len(strg)):
s = strg[i]
if s=="T": lis.append(s)
elif s=="L": lis.append(s)
elif s=="E": lis.append(s)
else:
num *= 10
num += int(s)
if i+1==len(strg) or (strg[i+1]=="T" or strg[i+1]=="L" or strg[i+1]=="E"):
lis.append(num)
num = 0ans = 0
index = 0
tp = 10def loop(num,ix):
global lis,index,tp,ans
index = ix
while lis[index] != "E":
n = lis[index]
index += 1
if n == "T": continue
elif n == "L": loop(int(lis[index]),index+1)
else:
ans += abs(n-tp)
tp = n
if num!=1:
loop(num-1,ix)
else:
index +=1
return
def scan():
global lis,ans,index,tp
while index != len(lis):
s = lis[index]
index+=1
if s == "T": continue
elif s == "L": loop(int(lis[index]),index+1)
else:
ans += abs(s-tp)
tp = s
scan()
print(ans)
我用遞迴解
也是40%
我的想法是L2T3T2T1=T3T2T1T3T2T1
(abs(a-b)+abs(b-c)*(Lx)+abs(headT-rearT)*(Lx-1)
但是打了好幾個小時都失敗