You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kattis竞赛题Left and Right超时(TLE)问题优化求助

Kattis竞赛题Left and Right超时(TLE)问题优化求助

我正在解决Kattis上的Left and Right问题,题目内容如下:

题目内容

Problem D: Left and Right

随着科技发展,现在可以用机器人投递邮件了!有一个位于长水平道路上的社区,道路上有n栋房子,从左到右编号为1到n。每天,送件机器人会收到一堆信件,每栋房子恰好有一封信。由于机械限制,机器人无法分拣信件,它总是查看堆顶的信件,前往对应的房子投递,重复这个过程直到所有信件都投递完毕。因此,每栋房子在一天的投递中恰好被访问一次。

机器人有一个跟踪设备记录其投递路线。有一天设备坏了,精确路线丢失了,但技术团队从损坏的设备中恢复了机器人的移动方向,用一个由n-1个字符组成的字符串表示。字符串的第i个字符是'L'(或'R'),表示机器人访问的第i+1栋房子在第i栋房子的左侧(或右侧)。例如,当n=4时,如果机器人访问顺序是2,4,3,1,那么移动方向字符串是"RLL"。

有了移动方向,可能可以确定机器人的访问顺序。技术团队请你编写程序来完成这个任务。可能有多个顺序能产生相同的移动方向,你需要找出字典序最小的那个。

输入

第一行是一个整数n(2 ≤ n ≤ 2×10⁵),第二行是一个长度为n-1的字符串,由'L'和'R'组成,表示机器人的移动方向。

输出

输出符合移动方向的字典序最小的机器人访问顺序。对于两个长度相同的不同整数序列A=(a₁,a₂,...,aₖ)和B=(b₁,b₂,...,bₖ),找到最小的索引i(1 ≤ i ≤ k)使得aᵢ≠bᵢ。如果aᵢ < bᵢ,则A的字典序比B小;反之则B更小。

样例输入1

3
LR

样例输出1

2
1
3

样例输入2

6
RLLRL

样例输出2

1
4
3
2
6
5

样例输入3

6
RRRLL

样例输出3

1
2
3
6
5
4

我的解决方案代码

我目前的思路是:

  1. 把初始的方向字符串按连续的'R'或'L'分组
  2. 遍历分组列表生成最终的访问序列
# 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")

遇到的问题

这段代码能正确解决题目,但提交时出现了**超时(Time Limit Exceeded, TLE)**错误,题目时间限制是1秒。我尝试了一些优化,但速度没有提升。

我不太懂Python里的快速输入方法,是不是可以从输入方面优化运行时间?或者有没有更高效的算法思路来解决这个问题?

备注:内容来源于stack exchange,提问作者SV Prime

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 15:45:30