{ }codelper
slicing listsreferencesP0439

Slice views that share cells, and copies

There is one array of n integers, and at first the name a points at the whole array.
A name always points at a few consecutive cells (a slice) inside some array.
The number of cells a name points at is that name's length, and the cells within a name are numbered from 1 at the front of its slice.
Process q commands in the given order.
- view x y l r: let x point at cells l through r (both included) of y.
No cells are copied, so x and y share those cells.
- copy x y l r: make a new array holding the current values of cells l through r of y, in order, and let x point at that whole new array.
- add x l r v: add v to each of cells l through r of x.
Every name pointing at those cells sees the new values.
- print x: on one line, print the values of the cells x points at, from x's cell 1 onward, separated by single spaces.
When view or copy makes x point at other cells, the values of the cells x pointed at before do not change.
Other names that pointed at those cells keep pointing at them.
x and y may be the same name.
Then l and r are counted on y as it was before the command.
If x is a name seen for the first time, view or copy creates it.
The first line gives n and q, the second line the n integers of the array, and the next q lines one command each.
Values on a line are separated by single spaces.
Print one line per print, in command order.
Try not copying cells on every cut: use a view your language provides, or remember 'which array, starting at which cell, how many cells'.
Grading looks only at the output.

Input
1 ≤ n ≤ 1,000, 1 ≤ q ≤ 1,000.
The array's integers and v are from -1,000 to 1,000 (plain digits, no commas).
Names are 1–10 lowercase letters or digits.
The y of view/copy and the x of add/print already exist.
For view, copy and add, with len the length of that name at that moment, 1 ≤ l ≤ r ≤ len.
There is at least one print, and all prints together output at most 20,000 numbers
Output
One line per print with the values of the cells it points at, separated by single spaces (plain digits, a leading - for negatives)
Example 1 · stdin
6 8
1 2 3 4 5 6
view b a 2 5
view c b 2 3
copy d b 1 2
add c 1 2 10
add a 1 6 1
print b
print c
print d
stdout
3 14 15 6
14 15
2 3
Example 2 · stdin
4 7
5 6 7 8
view a a 2 4
copy b a 2 3
view a a 2 2
add b 1 1 100
add a 1 1 -1
print a
print b
stdout
6
107 8
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 8 languages

This problem takes all 8 languages, but how you get 'a cut that does not copy' differs.
A Python list's a[l-1:r] is always a copy.
To share cells, wrap an array('i', …) in a memoryview.
Then m[l-1:r] is a view, and cutting a view again is still a view (make a copy with .tolist() and a new array).
Plain JS/TS arrays have no views, but Int32Array does: subarray(start, end) is a view, while the similarly named slice(start, end) is a copy.
Java ArrayList's subList(start, end) is a view, and values changed with set show in the original list.
Copy with new ArrayList<>(a.subList(…)).
In C#, ArraySegment<int> is a view and Slice(start, count) returns a view too.
ToArray() and List<int>.GetRange(start, count) make copies.
In C, a struct of 'address of the first cell + number of cells' is the view.
Adding l - 1 to the address gives a slice of a slice, and copying is malloc plus memcpy.
C++20's std::span<int> is a view and subspan(start, count) is a view too.
Keep copies in a std::deque<std::vector<int>>: appending to a deque never moves the arrays already in it, so spans into them stay valid.
Craykon's GetRange(start, count) always returns a new list, so there is no view.
Store [array number, start, length] for each name and build the view yourself.
Trap one: making view with the language's ordinary cut (Python a[l-1:r], JS/TS slice) makes a copy, so in example 1 neither add shows in b and the first line comes out 2 3 4 5.
Trap two: the reverse, making copy a view, ties the copy to the original cells.
In C, assigning just the Slice struct copies the address but still shares the cells, so example 1's d comes out 3 14.
Trap three: in a view of a view, counting l from the front of the array (not adding y's start) points at the wrong cells.
Example 1's c becomes cells 2–3 of the array instead of cells 2–3 of b (cells 3–4 of the array).
Trap four: functions that take a slice as 'start and end' (Python slicing, JS/TS subarray/slice, Java subList) are mixed with ones that take 'start and count' (C# Slice, C++ subspan, Craykon GetRange).
Passing a count as the second value, as in Java subList(l - 1, r - l + 1), gives the wrong length or an exception whenever l is not 1.

Pythonmain.py · 26 lines
import sysfrom array import array data = sys.stdin.read().split("\n")n, q = map(int, data[0].split())# 목록(list)을 a[l:r]로 자르면 복사본이 생긴다.# array를 memoryview로 감싸면 [l:r]가 같은 칸을 함께 쓰는 보기(view)를 준다.names = {"a": memoryview(array("i", map(int, data[1].split())))}out = []for line in data[2 : q + 2]:    p = line.split()    cmd = p[0]    if cmd == "view":        l, r = int(p[3]), int(p[4])        names[p[1]] = names[p[2]][l - 1 : r]  # 보기의 보기도 같은 칸을 가리킨다    elif cmd == "copy":        l, r = int(p[3]), int(p[4])        names[p[1]] = memoryview(array("i", names[p[2]][l - 1 : r].tolist()))  # 새 배열    elif cmd == "add":        v = names[p[1]]        l, r, d = int(p[2]), int(p[3]), int(p[4])        for i in range(l - 1, r):            v[i] += d    else:        out.append(" ".join(map(str, names[p[1]].tolist())))print("\n".join(out))
JavaScriptmain.js · 23 lines
const lines = require("fs").readFileSync(0, "utf8").split("\n");const q = Number(lines[0].split(" ")[1]);// Int32Array의 subarray(시작, 끝)는 같은 칸을 함께 쓰는 보기, slice(시작, 끝)는 복사본이다.const names = new Map([["a", Int32Array.from(lines[1].trim().split(" "), Number)]]);const out = [];for (let i = 2; i < q + 2; i++) {  const p = lines[i].trim().split(" ");  const cmd = p[0];  if (cmd === "view") {    const [l, r] = [Number(p[3]), Number(p[4])];    names.set(p[1], names.get(p[2]).subarray(l - 1, r)); // 같은 칸을 가리킨다  } else if (cmd === "copy") {    const [l, r] = [Number(p[3]), Number(p[4])];    names.set(p[1], names.get(p[2]).slice(l - 1, r)); // 새 배열  } else if (cmd === "add") {    const v = names.get(p[1]);    const [l, r, d] = [Number(p[2]), Number(p[3]), Number(p[4])];    for (let k = l - 1; k < r; k++) v[k] += d;  } else {    out.push(names.get(p[1]).join(" "));  }}console.log(out.join("\n"));
TypeScriptmain.ts · 26 lines
import { readFileSync } from "node:fs"; const lines: string[] = readFileSync(0, "utf8").split("\n");const q: number = Number(lines[0].split(" ")[1]);// Int32Array의 subarray(시작, 끝)는 같은 칸을 함께 쓰는 보기, slice(시작, 끝)는 복사본이다.const names = new Map<string, Int32Array>([["a", Int32Array.from(lines[1].trim().split(" "), Number)]]);const get = (name: string): Int32Array => names.get(name)!;const out: string[] = [];for (let i = 2; i < q + 2; i++) {  const p: string[] = lines[i].trim().split(" ");  const cmd: string = p[0];  if (cmd === "view") {    const l = Number(p[3]), r = Number(p[4]);    names.set(p[1], get(p[2]).subarray(l - 1, r)); // 같은 칸을 가리킨다  } else if (cmd === "copy") {    const l = Number(p[3]), r = Number(p[4]);    names.set(p[1], get(p[2]).slice(l - 1, r)); // 새 배열  } else if (cmd === "add") {    const v = get(p[1]);    const l = Number(p[2]), r = Number(p[3]), d = Number(p[4]);    for (let k = l - 1; k < r; k++) v[k] += d;  } else {    out.push(get(p[1]).join(" "));  }}console.log(out.join("\n"));
JavaMain.java · 47 lines
import java.io.BufferedReader;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map; public class Main {    public static void main(String[] args) throws Exception {        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));        String[] first = in.readLine().trim().split(" ");        int q = Integer.parseInt(first[1]);        List<Integer> base = new ArrayList<>();        for (String s : in.readLine().trim().split(" ")) base.add(Integer.parseInt(s));        // subList(시작, 끝)는 원래 목록의 칸을 함께 쓰는 보기다. 복사하려면 new ArrayList<>(…)로 감싼다.        Map<String, List<Integer>> names = new HashMap<>();        names.put("a", base);        StringBuilder out = new StringBuilder();        for (int i = 0; i < q; i++) {            String[] p = in.readLine().trim().split(" ");            switch (p[0]) {                case "view" -> {                    int l = Integer.parseInt(p[3]), r = Integer.parseInt(p[4]);                    names.put(p[1], names.get(p[2]).subList(l - 1, r)); // 같은 칸을 가리킨다                }                case "copy" -> {                    int l = Integer.parseInt(p[3]), r = Integer.parseInt(p[4]);                    names.put(p[1], new ArrayList<>(names.get(p[2]).subList(l - 1, r))); // 새 목록                }                case "add" -> {                    List<Integer> v = names.get(p[1]);                    int l = Integer.parseInt(p[2]), r = Integer.parseInt(p[3]), d = Integer.parseInt(p[4]);                    for (int k = l - 1; k < r; k++) v.set(k, v.get(k) + d);                }                default -> {                    List<Integer> v = names.get(p[1]);                    for (int k = 0; k < v.size(); k++) {                        if (k > 0) out.append(' ');                        out.append(v.get(k));                    }                    out.append('\n');                }            }        }        System.out.print(out);    }}
C#Main.cs · 46 lines
using System;using System.Collections.Generic;using System.Linq;using System.Text; class Program{    static void Main()    {        int q = int.Parse(Console.ReadLine()!.Trim().Split(' ')[1]);        int[] baseArr = Console.ReadLine()!.Trim().Split(' ').Select(int.Parse).ToArray();        // ArraySegment는 배열의 칸을 함께 쓰는 보기다. Slice(시작, 개수)도 보기를 주고, ToArray()는 복사본을 준다.        var names = new Dictionary<string, ArraySegment<int>> { ["a"] = new ArraySegment<int>(baseArr) };        var sb = new StringBuilder();        for (int i = 0; i < q; i++)        {            string[] p = Console.ReadLine()!.Trim().Split(' ');            switch (p[0])            {                case "view":                {                    int l = int.Parse(p[3]), r = int.Parse(p[4]);                    names[p[1]] = names[p[2]].Slice(l - 1, r - l + 1); // 같은 칸을 가리킨다                    break;                }                case "copy":                {                    int l = int.Parse(p[3]), r = int.Parse(p[4]);                    names[p[1]] = new ArraySegment<int>(names[p[2]].Slice(l - 1, r - l + 1).ToArray()); // 새 배열                    break;                }                case "add":                {                    ArraySegment<int> v = names[p[1]];                    int l = int.Parse(p[2]), r = int.Parse(p[3]), d = int.Parse(p[4]);                    for (int k = l - 1; k < r; k++) v[k] += d;                    break;                }                default:                    sb.Append(string.Join(" ", names[p[1]])).Append('\n');                    break;            }        }        Console.Write(sb);    }}
C++main.cpp · 48 lines
#include <deque>#include <iostream>#include <span>#include <string>#include <unordered_map>#include <vector> int main() {    std::ios::sync_with_stdio(false);    std::cin.tie(nullptr);    int n, q;    std::cin >> n >> q;    // 배열들을 deque에 둔다: 뒤에 넣어도 이미 든 배열의 자리가 옮겨지지 않아 span이 계속 맞다.    std::deque<std::vector<int>> arrays;    arrays.emplace_back(n);    for (int& v : arrays.back()) std::cin >> v;    // std::span은 칸을 함께 쓰는 보기다(C++20). subspan(시작, 개수)도 보기를 준다.    std::unordered_map<std::string, std::span<int>> names;    names["a"] = arrays.back();    std::string out;    for (int i = 0; i < q; i++) {        std::string cmd, x, y;        std::cin >> cmd >> x;        if (cmd == "view" || cmd == "copy") {            int l, r;            std::cin >> y >> l >> r;            std::span<int> s = names.at(y).subspan(l - 1, r - l + 1);            if (cmd == "copy") {                arrays.emplace_back(s.begin(), s.end()); // 칸을 새 배열로 복사한다                s = arrays.back();            }            names[x] = s;        } else if (cmd == "add") {            int l, r, d;            std::cin >> l >> r >> d;            std::span<int> s = names.at(x);            for (int k = l - 1; k < r; k++) s[k] += d;        } else {            std::span<int> s = names.at(x);            for (size_t k = 0; k < s.size(); k++) {                if (k) out += ' ';                out += std::to_string(s[k]);            }            out += '\n';        }    }    std::cout << out;}
Cmain.c · 65 lines
#include <stdio.h>#include <stdlib.h>#include <string.h> /* 조각: 어떤 배열 안의 첫 칸 주소와 칸 수. 주소를 담으므로 칸을 복사하지 않는다 */typedef struct {    int *p;    int len;} Slice; #define MAX_NAMES 2001static char names[MAX_NAMES][11];static Slice slices[MAX_NAMES];static int count = 0; static int *arrays[MAX_NAMES]; /* malloc으로 만든 배열들(마지막에 모두 풀어 준다) */static int arrays_count = 0; static int find(const char *name) {    for (int i = 0; i < count; i++)        if (strcmp(names[i], name) == 0) return i;    strcpy(names[count], name);    return count++;} static int *new_array(int len) {    int *p = malloc(sizeof(int) * len);    arrays[arrays_count++] = p;    return p;} int main(void) {    int n, q;    scanf("%d %d", &n, &q);    int *base = new_array(n);    for (int i = 0; i < n; i++) scanf("%d", &base[i]);    slices[find("a")] = (Slice){base, n};    for (int i = 0; i < q; i++) {        char cmd[8], x[11], y[11];        scanf("%7s %10s", cmd, x);        if (strcmp(cmd, "view") == 0 || strcmp(cmd, "copy") == 0) {            int l, r;            scanf("%10s %d %d", y, &l, &r);            Slice src = slices[find(y)];            Slice s = {src.p + (l - 1), r - l + 1}; /* 주소에 l - 1을 더하면 조각의 조각 */            if (cmd[0] == 'c') {                int *fresh = new_array(s.len);                memcpy(fresh, s.p, sizeof(int) * s.len); /* 칸을 새 배열로 복사한다 */                s.p = fresh;            }            slices[find(x)] = s;        } else if (strcmp(cmd, "add") == 0) {            int l, r, d;            scanf("%d %d %d", &l, &r, &d);            Slice s = slices[find(x)];            for (int k = l - 1; k < r; k++) s.p[k] += d;        } else {            Slice s = slices[find(x)];            for (int k = 0; k < s.len; k++) printf(k ? " %d" : "%d", s.p[k]);            putchar('\n');        }    }    for (int i = 0; i < arrays_count; i++) free(arrays[i]);    return 0;}
Craykonmain.cray · 51 lines
첫줄 = Console.ReadLine().Trim().Split();q = 첫줄[1].ToNumber();// 크레이콘의 부분목록(시작, 개수)은 늘 새 목록을 준다(보기가 없다).// 그래서 이름마다 [배열 번호, 배열 안의 시작 자리, 칸 수]를 기억한다.배열들 = [];처음 = [];foreach (s in Console.ReadLine().Trim().Split()){    처음.Add(s.ToNumber());}배열들.Add(처음);이름표 = Dict();이름표["a"] = [0, 0, 처음.Count];for (i = 0; i < q; i++){    p = Console.ReadLine().Trim().Split();    x = p[1];    switch (p[0])    {        case "view":            y정보 = 이름표[p[2]];            l = p[3].ToNumber();            r = p[4].ToNumber();            // 조각의 조각: y의 시작 자리에 l - 1을 더한다            이름표[x] = [y정보[0], y정보[1] + l - 1, r - l + 1];            break;        case "copy":            y정보 = 이름표[p[2]];            l = p[3].ToNumber();            r = p[4].ToNumber();            새배열 = 배열들[y정보[0]].GetRange(y정보[1] + l - 1, r - l + 1); // 새 목록            배열들.Add(새배열);            이름표[x] = [배열들.Count - 1, 0, 새배열.Count];            break;        case "add":            정보 = 이름표[x];            칸 = 배열들[정보[0]];            l = p[2].ToNumber();            r = p[3].ToNumber();            d = p[4].ToNumber();            for (k = 정보[1] + l - 1; k < 정보[1] + r; k++)            {                칸[k] = 칸[k] + d;            }            break;        default:            정보 = 이름표[x];            Console.WriteLine(배열들[정보[0]].GetRange(정보[1], 정보[2]).Join(" "));            break;    }}