{ }codelper
pointersP0417

Cutting, pasting and reversing video clips with prev and next pointers

n video clips, numbered 1 to n, are joined in a line in that order.
There are three commands.
- move a b c: of clip a and clip b, take the one that is currently earlier and the one that is currently later, cut out the run of clips from the earlier one to the later one, and paste it right after clip c.
If c is 0, paste it at the very front.
The order inside the run stays the same.
- However, if clip c is inside that run (clips a and b themselves included), move does nothing.
- rev a b: reverse the order of the run chosen in the same way.
- near x: print on one line the number of the clip right before clip x and the number of the clip right after it, separated by a single space.
If there is no clip before or after, print 0 in that place.
a and b may be equal; then the run is that one clip.
The first line gives n and the number of commands q, and the next q lines give one command each.
Print one line for each near, and on the last line print the n clip numbers from the front after all commands, separated by single spaces.
Try solving it with a doubly linked list where each clip holds its number and pointers prev and next to the clips before and after it.
If you add a head node numbered 0 and make the first clip's prev and the last clip's next point to it, you do not need to treat the two ends specially.
Create all nodes in one array at the start, and get the address of clip x's node directly as &nodes[x].
Reverse a run without copying numbers around: swap prev and next in every node of the run, then link the two ends of the run back to the nodes outside it.
Grading looks only at the output.

Input
1 ≤ n ≤ 10,000, 1 ≤ q ≤ 5,000.
a and b of move and rev, and x of near, are integers from 1 to n; c of move is an integer from 0 to n.
Output
One line per near (the numbers of the clips before and after), and on the last line the n clip numbers from the front
Example 1 · stdin
6 6
move 5 2 0
rev 1 3
near 2
move 1 4 3
move 3 1 1
near 6
stdout
0 1
4 0
2 3 1 5 4 6
Example 2 · stdin
5 7
rev 2 4
near 3
near 2
rev 5 1
near 5
near 4
move 4 4 2
stdout
4 2
3 5
0 2
3 1
5 2 4 3 1
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 · 2 languages

This problem accepts only C and C++.
Its topic is holding node addresses directly and relinking prev and next pointers.
Python, JavaScript, TypeScript, Java and Craykon can build the same shape with references but cannot work with addresses as pointer values, and C# uses pointers only inside unsafe.
Both solutions use a circular doubly linked list with a head node numbered 0.
The nodes live in static Node nodes[10001] in C and in a std::vector<Node> sized once at the start in C++, and neither ever grows, so the Node * pointers you hold stay valid to the end.
Cutting out is the two lines a->prev->next = b->next; b->next->prev = a->prev; and pasting is four lines, so however long the run is, only six pointers change.
Reversing swaps prev and next in every node of the run; you must grab after = p->next before the swap to get to the next node.
The function that puts two pointers into front-to-back order takes Node **a in C and a reference to a pointer, Node *&a, in C++.
Which end of the run comes first is found by walking from a along next and checking whether you meet b.
So one command takes time proportional to the number of clips, which is plenty fast for this problem's n and q.
In C++, std::list::splice moves a run within the same list in constant time, so it also works for move.
Four traps: ① Comparing the ends by address, as in if (*a > *b), is wrong.
Comparing pointers into the same array is valid C, but the order of addresses in the array is only the original numbering, not the order after edits.
In rev 1 3 of example 1, clip 3 is now before clip 1 but its address is larger, so the walk goes from 1 along next through the head node and reverses that too, and the very first line comes out as 3 0.
② If you do not check whether c is inside the run, the run gets pasted inside the run you just cut out and clips vanish from the list.
That is what move 3 1 1 in example 1 does, and the last line becomes 2 5 4 6.
③ If after a reversal you forget right->prev = a;, which fixes the prev of the node right after the run, that node's prev still points to the old b.
In example 2 the next rev 5 1 turns that wrong pointer into a next, so near 5 prints 0 4 (should be 0 2) and clip 2 vanishes from the last line.
④ In C++, if you use a std::list<int> with a table of iterators by number and reverse with std::reverse(x, std::next(y)), std::reverse does not move the nodes but swaps the values inside them.
The table's iterators now point at nodes holding other numbers, and near 6 in example 1 prints 3 0 (should be 4 0).
std::list::reverse reverses only the whole list, so a run has to be reversed by moving the nodes yourself.

C++main.cpp · 99 lines
#include <iostream>#include <string>#include <utility>#include <vector> struct Node {    int id;    Node *prev;    Node *next;}; // 머리 노드(번호 0)를 둔 원형 이중 연결 리스트.// 노드는 처음에 한 번만 만들고 다시 늘리지 않으니, 쥐어 둔 Node*가 계속 맞다.class Clips {public:    explicit Clips(int n) : nodes_(n + 1) {        for (int i = 0; i <= n; i++) {            nodes_[i].id = i;            nodes_[i].prev = &nodes_[i == 0 ? n : i - 1];            nodes_[i].next = &nodes_[i == n ? 0 : i + 1];        }    }     Node *at(int x) { return &nodes_[x]; }     void move(Node *a, Node *b, Node *c) {        order(a, b);        if (inside(a, b, c)) return;        a->prev->next = b->next;  // 떼어 내기        b->next->prev = a->prev;        a->prev = c;              // c 바로 뒤에 붙이기        b->next = c->next;        c->next->prev = b;        c->next = a;    }     void reverse(Node *a, Node *b) {        order(a, b);        Node *left = a->prev, *right = b->next;        for (Node *p = a; p != right;) {            Node *after = p->next;  // 바꾸기 전에 다음 노드를 쥐어 둔다            std::swap(p->prev, p->next);            p = after;        }        left->next = b;        b->prev = left;        right->prev = a;        a->next = right;    }     void print(std::ostream &out) {        for (Node *p = head()->next; p != head(); p = p->next)            out << p->id << (p->next == head() ? '\n' : ' ');    } private:    std::vector<Node> nodes_;    Node *head() { return &nodes_[0]; }     // 포인터 a, b를 참조로 받아, a가 앞에 오도록 바꿔 넣는다    void order(Node *&a, Node *&b) {        for (Node *p = a; p != head(); p = p->next)            if (p == b) return;        std::swap(a, b);    }     static bool inside(const Node *a, const Node *b, const Node *c) {        for (const Node *p = a;; p = p->next) {            if (p == c) return true;            if (p == b) return false;        }    }}; int main() {    std::ios::sync_with_stdio(false);    std::cin.tie(nullptr);    int n, q;    std::cin >> n >> q;    Clips clips(n);    std::string cmd;    for (int k = 0; k < q; k++) {        int a, b, c;        std::cin >> cmd;        if (cmd == "move") {            std::cin >> a >> b >> c;            clips.move(clips.at(a), clips.at(b), clips.at(c));        } else if (cmd == "rev") {            std::cin >> a >> b;            clips.reverse(clips.at(a), clips.at(b));        } else {            std::cin >> a;            const Node *x = clips.at(a);            std::cout << x->prev->id << ' ' << x->next->id << '\n';        }    }    clips.print(std::cout);    return 0;}
Cmain.c · 92 lines
#include <stdio.h>#include <string.h> typedef struct Node {    int id;    struct Node *prev, *next;} Node; /* nodes[0]은 머리 노드(번호 0): 첫 조각의 prev와 마지막 조각의 next가 여기를 가리킨다.   nodes[x]는 x번 조각이라, 번호로 바로 그 노드의 주소를 얻는다 */static Node nodes[10001];static Node *head = &nodes[0]; /* a에서 next로 걸어 b를 만나면 a가 앞(같아도 앞으로 친다) */static int comes_first(const Node *a, const Node *b) {    for (const Node *p = a; p != head; p = p->next)        if (p == b) return 1;    return 0;} /* *a가 앞, *b가 뒤가 되게 두 포인터를 바꿔 넣는다 */static void order(Node **a, Node **b) {    if (!comes_first(*a, *b)) {        Node *t = *a;        *a = *b;        *b = t;    }} static int inside(const Node *a, const Node *b, const Node *c) {    for (const Node *p = a;; p = p->next) {        if (p == c) return 1;        if (p == b) return 0;    }} static void move(Node *a, Node *b, Node *c) {    order(&a, &b);    if (inside(a, b, c)) return;    /* 떼어 내기: 양옆을 서로 잇는다 */    a->prev->next = b->next;    b->next->prev = a->prev;    /* c 바로 뒤에 붙이기 */    a->prev = c;    b->next = c->next;    c->next->prev = b;    c->next = a;} static void reverse(Node *a, Node *b) {    order(&a, &b);    Node *left = a->prev, *right = b->next;    for (Node *p = a; p != right;) {        Node *after = p->next; /* 바꾸기 전에 다음 노드를 쥐어 둔다 */        p->next = p->prev;        p->prev = after;        p = after;    }    /* 구간 바깥 두 노드와 구간의 두 끝을 양쪽 방향으로 다시 잇는다 */    left->next = b;    b->prev = left;    right->prev = a;    a->next = right;} int main(void) {    int n, q;    if (scanf("%d %d", &n, &q) != 2) return 0;    for (int i = 0; i <= n; i++) {        nodes[i].id = i;        nodes[i].prev = &nodes[i == 0 ? n : i - 1];        nodes[i].next = &nodes[i == n ? 0 : i + 1];    }    char cmd[8];    for (int k = 0; k < q; k++) {        int a, b, c;        scanf("%7s", cmd);        if (strcmp(cmd, "move") == 0) {            scanf("%d %d %d", &a, &b, &c);            move(&nodes[a], &nodes[b], &nodes[c]);        } else if (strcmp(cmd, "rev") == 0) {            scanf("%d %d", &a, &b);            reverse(&nodes[a], &nodes[b]);        } else {            scanf("%d", &a);            printf("%d %d\n", nodes[a].prev->id, nodes[a].next->id);        }    }    for (const Node *p = head->next; p != head; p = p->next)        printf("%d%c", p->id, p->next == head ? '\n' : ' ');    return 0;}