[Python] Left and Right Contest Question TLE Kattis

Discussão em 'Python' iniciado por Stack, Dezembro 1, 2024.

  1. Stack

    Stack Membro Participativo

    I'm getting TLE (Time Limit Exceeded) for this contest question and I'm trying to increase the speed of my program. Here is the question:

    Kattis website: https://open.kattis.com/contests/en6o4k/problems/leftandright

    Alternative viewform: Left and Right Contest Question.

    I don't fully understand fast input for python so that would also be appreciated if someone could explain, perhaps that could help with the runtime.

    Here is the code I have developed to solve the question:

    # My method is to:
    # 1. group blocks of the initial Left Right sequence
    # 2. loop through the groups list to get the sequence

    n = int(input())
    word = input()+"a" # adding in "a" for the grouping algorithm

    groups = [] # list for grouping string by blocks of "R" and "L"
    seq = [] # final sequence the robot moves

    pos = 1 if word[0] == "R" else 0 # position will always start with 1 if the robot is moving right first

    if pos == 1:
    seq = [1]

    # grouping algorithm
    group = word[0]
    for i in word[1:]:
    if i==group[0]:
    group+=i
    else:
    groups.append(group)
    group=i

    # sequence algorithm
    for c, i in enumerate(groups):
    if "R" in i:
    for j in i[:-1]:
    pos+=1
    seq.append(pos)

    if c+1 == len(groups):
    seq.append(pos+1)

    else:
    pos+=len(i)+1
    seq.append(pos)
    for k in range(len(i)):
    seq.append(pos-1-k)

    print(*seq, sep ="\n")


    The program works and solves the question, however the time limit for the question is 1 second and I cannot find a faster method. I'm looking to reduce the runtime if someone could post their code or explain an alternative to solve the question more efficiently.

    Thank you.

    Continue reading...

Compartilhe esta Página