首页 > 试题广场 >

小美的彩带

[编程题]小美的彩带
  • 热度指数:2040 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
小美的彩带是由一条长度为 n 的彩带一直无限循环得到的,彩带的每一个位置都有一个颜色,用 a_i 表示。因此当 i>n 时, a_i=a_{i-n} 。

小美每次会从左往右或从右往左剪一段长度为 x 的彩带,她想知道她每次剪下来的彩带有多少种颜色。


输入描述:
\,\,\,\,\,\,\,\,\,\,第一行输入两个整数 n,q\left(1 \leq n,q \leq 2 \times 10^5\right) 代表彩带长度、剪彩带次数。
\,\,\,\,\,\,\,\,\,\,第二行输入 n 个整数 a_1,a_2,\dots,a_n\left(1 \leq a_i \leq 10^9\right) 代表彩带每一个位置的颜色。
\,\,\,\,\,\,\,\,\,\,此后 q 行,每行输入一个字符 c 和一个整数 x\left(1 \leq x \leq 10^9;\ c\in {\tt 'L'} , {\tt 'R'}\right) 代表裁剪方向和裁剪长度,其中 '\tt L说明从左往右剪, '\tt R' 说明从右往左剪 。


输出描述:
\,\,\,\,\,\,\,\,\,\,对于每一次裁剪彩带,在一行上输出一个整数代表颜色数量。
示例1

输入

6 4
1 1 4 5 1 4
L 2
L 3
R 12
R 1

输出

1
3
3
1

说明

\,\,\,\,\,\,\,\,\,\,第一次剪彩带,剪下来的是 [1,1] ,有 \{1\}1 种颜色;
\,\,\,\,\,\,\,\,\,\,第二次剪彩带,剪下来的是 [4,5,1] ,有 \{1,4,5\}3 种颜色;
\,\,\,\,\,\,\,\,\,\,第三次剪彩带,剪下来的是 [4,1,5,4,1,1,4,1,5,4,1,1] ,有 \{1,4,5\}3 种颜色。
\,\,\,\,\,\,\,\,\,\,第四次剪彩带,剪下来的是 [4] ,有 \{4\} 这一种颜色。
第二组用例超时
每次裁剪都根据颜色循环拼接一个新的color_left或color_right,颜色输出set的长度
def solve(color_left, color_right, c, x):
    color_set = set(color_left)
    full_color_count = 0
 
    if x >= len(color_left):
        x = x % len(color_left)
        full_color_count = len(color_set)
 
    if c == "L":
        cut_arr = color_left[:x]
        cut_set = set(cut_arr)
        color_count = len(cut_set)
 
        new_left = color_left[x:]
        new_left.extend(cut_arr)
 
        if full_color_count:
            return new_left, color_right, full_color_count
        else:
            return new_left, color_right, color_count
 
    elif c == "R":
        cut_arr = color_right[:x]
        cut_set = set(cut_arr)
        color_count = len(cut_set)
 
        new_right = color_right[x:]
        new_right.extend(cut_arr)
         
        if full_color_count:
            return color_left, new_right, full_color_count
        else:
            return color_left, new_right, color_count
 
if __name__ == "__main__":
    n, q = list(map(int, input().split()))
    color_left = list(map(int, input().split()))
    color_right = color_left.copy()
    color_right.reverse()
     
    for _ in range(q):
        c, x = list(input().split())
        x = int(x)
        color_left, color_right, ans = solve(color_left, color_right, c, x)
        print(ans)


发表于 2024-10-28 00:37:50 回复(0)