{ }codelper
列表切片复制列表删除元素P0298

复制、剪切再粘贴

有一个装着 n 个整数的列表,和一个开始时为空的剪贴板。
按给出的顺序处理 q 条命令。
copy l r 把当前列表的第 l 个到第 r 个(两端都包含)复制到剪贴板。
列表不变。
cut l r 把当前列表的第 l 个到第 r 个(两端都包含)移到剪贴板,并从列表中删去。
copy 和 cut 会清掉剪贴板里原来的内容,换成新的片段。
paste p 把剪贴板里的内容按原顺序插到当前列表第 p 个数的后面。
p 为 0 时插到最前面。
粘贴之后剪贴板保持不变。
粘贴空的剪贴板什么也不发生。
如果粘贴后列表的个数会超过 M,这条 paste 被忽略(正好变成 M 个的要粘贴)。
编号把最前面的数算作 1。
第一行给出 n 和 M,第二行给出 n 个整数,第三行给出 q,接下来 q 行每行一条命令。
一行中的值用一个空格隔开。
所有命令执行完后,第一行输出列表的个数,第二行按顺序输出列表中的数,用一个空格隔开。
如果列表为空,第二行输出 -。

输入
1 ≤ n ≤ 1,000,n ≤ M ≤ 5,000,1 ≤ q ≤ 500(只给出数字,不带逗号)。
列表中的数在 -999 到 999 之间。
copy 和 cut:设当时列表的个数为 len,则 1 ≤ l ≤ r ≤ len(列表为空时不会给出)。
paste:0 ≤ p ≤ len
输出
第一行是列表的个数,第二行是列表中的数(用一个空格隔开)或 -
样例 1 · stdin
5 8
10 20 30 40 50
7
copy 2 3
paste 5
cut 1 2
paste 0
paste 3
cut 4 7
paste 1
stdout
7
10 40 50 20 30 20 30
main.py
输入(stdin)

运行时这些行会依次作为 input()/标准输入传入(运行中不会等待输入)。

$ 就绪

请在电脑上打开以编写和运行代码。在手机上可以查看题目和题解。

其他语言怎么写?查看各语言题解 · 8 种语言题解

指明一个片段的方式分成“起点和终点”与“起点和个数”两类。
起点和终点(不含终点):Python a[l-1:r],JS・TS a.slice(l - 1, r),Java a.subList(l - 1, r),C++ 用两个迭代器 a.begin() + (l - 1), a.begin() + r。
起点和个数:C# a.GetRange(l - 1, r - l + 1),Craykon a.子列表(l - 1, r - l + 1),C memcpy(clip, a + l - 1, 个数 * sizeof(int))。
就在 JS 里,slice(起点, 终点) 和 splice(起点, 个数) 也不一样。
删除:Python del a[l-1:r],JS・TS a.splice(l - 1, 个数)(它返回删掉的部分,所以 cut 只要一行),Java a.subList(l - 1, r).clear(),C# RemoveRange(起点, 个数),C++ a.erase(开头, 结尾),C memmove。
插入:Python a[p:p] = clip,JS・TS a.splice(p, 0, ...clip),Java a.addAll(p, clip),C# a.InsertRange(p, clip),C++ a.insert(位置, 开头, 结尾),C 先用 memmove 把后面挪开再 memcpy。
Craykon 没有一次删除或插入多个的功能,所以在前一段 子列表(0, p) 后面用 添加 接上剪贴板和后一段,做成新列表。
陷阱 ① 把终点和个数弄反:slice(l - 1, r - l + 1) 或 GetRange(l - 1, r)。
JS 和 Python 越界时不报错而是悄悄截短,C#・Java・Craykon 报错停下。
② 是副本还是窗口:Python 切片、JS slice、C# GetRange、Craykon 子列表 给出新列表,而 Java 的 subList 是看向原列表的窗口。
把窗口直接当剪贴板,在列表插入或删除之后再用这个窗口就会抛出 ConcurrentModificationException。
用 new ArrayList<>(a.subList(l - 1, r)) 做副本。
③“第 p 个的后面”就是从 0 数的下标 p。
写成 p - 1 的话,p = 0 时 Python 变成 a[-1:-1],插到最后一个数的前面。
④ 上限要用粘贴后的个数 当前个数 + 剪贴板个数 来比,正好 M 个要粘贴(<=)。
⑤ cut 也会把剪贴板换成新的片段。
⑥ 第 r 个也属于片段。

Pythonmain.py · 24 行
import sys lines = sys.stdin.read().split("\n")n, limit = map(int, lines[0].split())a = list(map(int, lines[1].split()))q = int(lines[2])clip = []  # 오려 두기 판 for line in lines[3:3 + q]:    p = line.split()    if p[0] == "copy":        l, r = int(p[1]), int(p[2])        clip = a[l - 1:r]  # 조각은 새 목록(사본)이다    elif p[0] == "cut":        l, r = int(p[1]), int(p[2])        clip = a[l - 1:r]        del a[l - 1:r]    else:        at = int(p[1])        if len(a) + len(clip) <= limit:            a[at:at] = clip  # 빈 조각 자리에 넣으면 끼워 넣기가 된다 print(len(a))print(" ".join(map(str, a)) if a else "-")
JavaScriptmain.js · 22 行
const lines = require("fs").readFileSync(0, "utf8").split("\n");const limit = Number(lines[0].trim().split(" ")[1]);const a = lines[1].trim().split(" ").map(Number);const q = Number(lines[2]);let clip = []; // 오려 두기 판 for (const line of lines.slice(3, 3 + q)) {  const p = line.trim().split(" ");  if (p[0] === "copy") {    const l = Number(p[1]), r = Number(p[2]);    clip = a.slice(l - 1, r); // slice(시작, 끝): 끝은 들어가지 않는다. 사본을 준다  } else if (p[0] === "cut") {    const l = Number(p[1]), r = Number(p[2]);    clip = a.splice(l - 1, r - l + 1); // splice(시작, 개수): 뺀 것들을 돌려준다  } else {    const at = Number(p[1]);    if (a.length + clip.length <= limit) a.splice(at, 0, ...clip);  }} console.log(a.length);console.log(a.length > 0 ? a.join(" ") : "-");
TypeScriptmain.ts · 24 行
import { readFileSync } from "node:fs"; const lines: string[] = readFileSync(0, "utf8").split("\n");const limit = Number(lines[0].trim().split(" ")[1]);const a: number[] = lines[1].trim().split(" ").map(Number);const q = Number(lines[2]);let clip: number[] = []; // 오려 두기 판 for (const line of lines.slice(3, 3 + q)) {  const p = line.trim().split(" ");  if (p[0] === "copy") {    const l = Number(p[1]), r = Number(p[2]);    clip = a.slice(l - 1, r); // slice(시작, 끝): 끝은 들어가지 않는다. 사본을 준다  } else if (p[0] === "cut") {    const l = Number(p[1]), r = Number(p[2]);    clip = a.splice(l - 1, r - l + 1); // splice(시작, 개수): 뺀 것들을 돌려준다  } else {    const at = Number(p[1]);    if (a.length + clip.length <= limit) a.splice(at, 0, ...clip);  }} console.log(a.length);console.log(a.length > 0 ? a.join(" ") : "-");
JavaMain.java · 43 行
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.List;import java.util.StringTokenizer; public class Main {    public static void main(String[] args) throws IOException {        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));        int limit = Integer.parseInt(in.readLine().trim().split(" ")[1]);        List<Integer> a = new ArrayList<>();        StringTokenizer st = new StringTokenizer(in.readLine());        while (st.hasMoreTokens()) a.add(Integer.parseInt(st.nextToken()));        int q = Integer.parseInt(in.readLine().trim());        List<Integer> clip = new ArrayList<>(); // 오려 두기 판         for (int t = 0; t < q; t++) {            String[] p = in.readLine().trim().split(" ");            if (p[0].equals("copy")) {                int l = Integer.parseInt(p[1]), r = Integer.parseInt(p[2]);                // subList는 원래 목록을 들여다보는 창이라서, 새 목록에 담아 사본으로 만든다                clip = new ArrayList<>(a.subList(l - 1, r));            } else if (p[0].equals("cut")) {                int l = Integer.parseInt(p[1]), r = Integer.parseInt(p[2]);                clip = new ArrayList<>(a.subList(l - 1, r));                a.subList(l - 1, r).clear(); // 창을 비우면 원래 목록에서 빠진다            } else {                int at = Integer.parseInt(p[1]);                if (a.size() + clip.size() <= limit) a.addAll(at, clip);            }        }         StringBuilder out = new StringBuilder();        out.append(a.size()).append('\n');        if (a.isEmpty()) out.append('-');        for (int i = 0; i < a.size(); i++) {            if (i > 0) out.append(' ');            out.append(a.get(i));        }        System.out.println(out);    }}
C#Main.cs · 38 行
using System;using System.Collections.Generic;using System.Linq; class Program{    static void Main()    {        int limit = int.Parse(Console.ReadLine().Trim().Split(' ')[1]);        List<int> a = Console.ReadLine().Trim().Split(' ').Select(int.Parse).ToList();        int q = int.Parse(Console.ReadLine().Trim());        var clip = new List<int>(); // 오려 두기 판         for (int t = 0; t < q; t++)        {            string[] p = Console.ReadLine().Trim().Split(' ');            if (p[0] == "copy")            {                int l = int.Parse(p[1]), r = int.Parse(p[2]);                clip = a.GetRange(l - 1, r - l + 1); // GetRange(시작, 개수): 사본을 준다            }            else if (p[0] == "cut")            {                int l = int.Parse(p[1]), r = int.Parse(p[2]);                clip = a.GetRange(l - 1, r - l + 1);                a.RemoveRange(l - 1, r - l + 1);            }            else            {                int at = int.Parse(p[1]);                if (a.Count + clip.Count <= limit) a.InsertRange(at, clip);            }        }         Console.WriteLine(a.Count);        Console.WriteLine(a.Count > 0 ? string.Join(" ", a) : "-");    }}
C++main.cpp · 34 行
#include <iostream>#include <string>#include <vector> int main() {    std::ios::sync_with_stdio(false);    std::size_t n, limit;    std::cin >> n >> limit;    std::vector<int> a(n), clip; // clip: 오려 두기 판    for (int& x : a) std::cin >> x;    int q;    std::cin >> q;     for (int t = 0; t < q; t++) {        std::string cmd;        std::cin >> cmd;        if (cmd == "paste") {            int at;            std::cin >> at;            if (a.size() + clip.size() <= limit) a.insert(a.begin() + at, clip.begin(), clip.end());        } else {            int l, r;            std::cin >> l >> r;            // 반복자 두 개 [시작, 끝)로 조각을 가리킨다. assign은 사본을 만든다            clip.assign(a.begin() + (l - 1), a.begin() + r);            if (cmd == "cut") a.erase(a.begin() + (l - 1), a.begin() + r);        }    }     std::cout << a.size() << '\n';    if (a.empty()) std::cout << '-';    for (std::size_t i = 0; i < a.size(); i++) std::cout << (i ? " " : "") << a[i];    std::cout << '\n';}
Cmain.c · 43 行
#include <stdio.h>#include <string.h> #define MAX 5000 static int a[MAX], clip[MAX]; int main(void) {    int n, limit, q, clipLen = 0;    scanf("%d %d", &n, &limit);    for (int i = 0; i < n; i++) scanf("%d", &a[i]);    scanf("%d", &q);     for (int t = 0; t < q; t++) {        char cmd[8];        scanf("%7s", cmd);        if (strcmp(cmd, "paste") == 0) {            int at;            scanf("%d", &at);            if (n + clipLen <= limit) {                /* 뒤쪽을 조각 길이만큼 밀고(겹치므로 memmove) 빈 곳에 조각을 베낀다 */                memmove(a + at + clipLen, a + at, (size_t)(n - at) * sizeof(int));                memcpy(a + at, clip, (size_t)clipLen * sizeof(int));                n += clipLen;            }        } else {            int l, r;            scanf("%d %d", &l, &r);            clipLen = r - l + 1;            memcpy(clip, a + l - 1, (size_t)clipLen * sizeof(int)); /* 조각을 따로 베껴 둔다 */            if (strcmp(cmd, "cut") == 0) {                memmove(a + l - 1, a + r, (size_t)(n - r) * sizeof(int));                n -= clipLen;            }        }    }     printf("%d\n", n);    if (n == 0) printf("-");    for (int i = 0; i < n; i++) printf(i ? " %d" : "%d", a[i]);    printf("\n");    return 0;}
Craykonmain.cray · 54 行
첫줄 = 控制台.读数字();limit = 첫줄[1];a = 控制台.读数字();q = 控制台.读行().转数字();clip = []; // 목록 뒤에 다른 목록의 것들을 차례로 붙인다붙이기(목록, 더할것){    遍历 (x 在 더할것)    {        목록.添加(x);    }} 循环 (t = 0; t < q; t++){    p = 控制台.读行().去空白().分割(" ");    如果 (p[0] == "paste")    {        at = p[1].转数字();        如果 (a.数量 + clip.数量 <= limit)        {            // 앞 조각 + 오려 둔 것 + 뒤 조각            뒤 = a.子列表(at, a.数量 - at);            a = a.子列表(0, at);            붙이기(a, clip);            붙이기(a, 뒤);        }    }    否则    {        l = p[1].转数字();        r = p[2].转数字();        // 부분목록(시작, 개수)는 새 목록(사본)을 준다        clip = a.子列表(l - 1, r - l + 1);        如果 (p[0] == "cut")        {            뒤 = a.子列表(r, a.数量 - r);            a = a.子列表(0, l - 1);            붙이기(a, 뒤);        }    }} 控制台.输出(a.数量);如果 (a.数量 > 0){    控制台.输出(a.连接(" "));}否则{    控制台.输出("-");}