insert(t, x): Insert an integer x at the end of Lt.
dump(t): Print all elements in Lt.
splice(s, t): Transfer elements of Ls to the end of Lt. becomes empty.
In the initial state, Li(i=0,1,...,n−1) are empty.
Constraints
1≤n≤1,000
1≤q≤500,000
For a splice operation, s=t
For a splice operation, Ls is not empty
The total number of elements printed by dump operations do not exceed 1,000,000
−1,000,000,000≤x≤1,000,000,000
Input
The input is given in the following format.
nqquery1query2
:
queryq
Each query queryi is given by
0 tx
or
1 t
or
2 st
where the first digits 0, 1 and 2 represent insert, dump and splice operations respectively.
Output
For each dump operation, print elements of the corresponding list in a line. Separete adjacency elements by a space character (do not print the space after the last element). Note that, if the list is empty, an empty line should be printed.
We need to design a data structure that supports these operations efficiently.
We have up to n=1000 lists. q up to 500k. Splice transfers all elements from list s to the end of list t, and makes s empty. Insert adds an element to the end. Dump prints all elements. The total number of printed elements is <= 1e6, so that's fine.
We need to implement operations efficiently: Insert O(1) or amortized. Splice should be O(1) ideally, because we cannot copy all elements each time (could be many elements). Since total elements inserted across all lists is at most the number of insert operations (q, but also elements are moved, but total elements inserted <= q). But if we do many splices, copying could be costly. So we need a way to concatenate lists in O(1) time.
We could use linked lists with head/tail pointers. For each list we maintain a singly linked list (or double) and we can merge by appending the head of list s to tail of list t and updating tail. But careful: we need to maintain order: elements inserted in order, and when we splice, we transfer all elements of L_s to end of L_t, preserving order. If we use singly linked list, we need to keep tail. To merge L_s into L_t: set tail[t].next = head[s]; update tail[t] = tail[s]; then set head[s]=null, tail[s]=null. That's O(1). However, we also need to be able to dump the elements in order. Dumping a list requires traversing from head to tail. If we do many splices, the list structures become interleaved but still each element belongs to exactly one list at any time. That is fine.
But we must also support insert at end: if we maintain tail, we can add a node and update tail. Insert O(1). Dump traverses list, printing elements. The total printed elements ≤ 1e6, so total dump traversal cost is acceptable.
Now, what about the constraint that for splice, L_s is not empty? So we don't worry about empty merges? But we can handle anyway.
Seems simple. However, there is a catch: after splicing, L_s becomes empty, but later we might insert into L_s again. That's fine.
Thus we can implement with singly linked list nodes, each storing value, next pointer. For each list i, maintain head[i], tail[i].
But careful: when we splice s into t, we need to handle case where t is empty: then head[t]=head[s], tail[t]=tail[s]. Then set head[s]=null, tail[s]=null.
That's O(1). Works.
However, note that we have up to n=1000, q=500k, so total nodes <= number of inserts = at most q (since each insert creates one node) = 500k. Memory is fine.
Now dump operation: we need to print elements in order. For each list, we traverse from head to tail. However, if we have performed many splices, the list might be long; but dump total printed elements is limited to 1e6, so fine.
But there is a subtle point: When we splice, we attach the whole list s to t. However, if we later insert into s again, that's a new list. That's fine.
Thus we can implement straightforwardly.
But we need to be careful about data structures for large q: Using dynamic allocation for nodes: we can use arrays of size maxInserts (500k) storing value and next index (int). We can allocate nodes sequentially from an array. Use -1 for null. Or use vector of struct Node. But to be safe with performance, we can pre-allocate a large array (maybe 500001). In C++ we can use vector of Node and push_back each insert.
But note: after a splice, the nodes originally from s now become part of t. We don't need to delete nodes. So we need to keep track of them.
Thus algorithm:
Initialize:
head = vector(n, -1)
tail = vector(n, -1)
Node struct: val, next (int)
For each query:
if type == 0 (insert t x):
create node with val=x, next=-1
if head[t]==-1: head[t]=nodeIdx; tail[t]=nodeIdx;
else: next[tail[t]]=nodeIdx; tail[t]=nodeIdx;
if type == 1 (dump t):
traverse from head[t] and output values in order; if empty, print newline.
if type == 2 (splice s t):
if head[s]==-1: (should not happen as per problem, but we can handle: do nothing) but problem says L_s not empty.
else:
if head[t]==-1:
head[t] = head[s];
tail[t] = tail[s];
else:
next[tail[t]] = head[s];
tail[t] = tail[s];
head[s] = tail[s] = -1;
That's all.
But need to consider: what if s == t? Problem says s != t.
Potential issue: After splicing, some nodes may have been transferred, and later we insert into s. That's fine.
Now we need to output dump: separate by spaces, no trailing space, then newline. For empty, just newline.
Seems trivial.
But wait: The problem constraints include: "The total number of elements printed by dump operations do not exceed 1,000,000". So we will be fine.
But is there any hidden complexity? For large n, many lists, but operations are okay.
I think this is indeed the intended solution: O(1) per operation.
But maybe there is a catch: If we use singly linked list, we need to update tail[t] to tail[s] correctly. However, after splicing, we have attached the entire chain. But what about if we later do dump on t, we traverse from head[t] to tail[t] via next pointers. That works because the list is singly linked and we maintain tail.
Now, we must ensure that next pointers are properly set. For insert, we set next[tail[t]] to new node and update tail. For splice, we set next[tail[t]] to head[s] if tail[t] exists.
One more thought: The order of operations: When we splice, we transfer elements of L_s to the end of L_t. If we attach head[s] to tail[t], and update tail[t] to tail[s], that's correct. But what about the case where t is empty? Then tail[t] is -1, we must avoid accessing next[ -1 ]. So we handle separately.
That's it.
Now, regarding memory: Node array can be of size q+1 if we index from 0. We'll use vector and push_back.
Let's test with example:
n=3
Inserts:
0 0 1 -> node0, head0=0,tail0=0
0 0 2 -> node1, next[0]=1, tail0=1
0 0 3 -> node2, next[1]=2, tail0=2
0 1 4 -> node3, head1=3,tail1=3
0 1 5 -> node4, next[3]=4, tail1=4
2 1 0 -> s=1 t=0: head0=0,tail0=2; head1=3,tail1=4. Since t non-empty, next[tail0]=next[2]=head1=3, then tail0=tail1=4. head1=-1,tail1=-1.
0 2 6 -> node5, head2=5,tail2=5
dump0: traverse from head0: 0->1->2->3->4? Wait: chain: 0->1->2->? after splice, next[2]=3. And 3->4. So values: node0=1, node1=2, node2=3, node3=4, node4=5. So prints "1 2 3 4 5". Good.
dump1: head1=-1, empty line.
dump2: prints 6.
Works.
Now, the potential problem: If we have many splices, the linked list might become very long, and dumping could be O(length). But total printed ≤ 1e6, so it's okay. However, if we have many dump operations on the same long list, each dump would traverse the whole list, but if that list has many elements and we dump it many times, total printed may exceed 1e6? Actually, the problem states total number of elements printed by dump operations does not exceed 1e6. That means sum of lengths of all lists when dump is called is ≤1e6. So total traversal cost across all dumps is bounded by 1e6. So it's fine.
Thus the straightforward approach passes.
But is there any scenario where the simple singly linked list approach fails because we need to update pointers when we later insert into s? We reset head[s] and tail[s] to -1 after splice, so subsequent inserts into s start a fresh list. That's correct.
Now, implementation details:
We'll store nodes in a vector. Node {int val; int next;}. Possibly use struct with constructor.
We'll store head and tail as vectors of int (size n) initialized to -1.
Processing queries:
We read q. For each query, read first integer typ.
If typ == 0: read t, x. Insert.
If typ == 1: read t. Dump: if head[t]==-1: print newline. else traverse: start = head[t]; while start != -1: collect values into a vector? But we need to print them space separated. We can traverse and print each value with a space before except first. But that requires checking first. Typically we output first value then for each subsequent output space before. Or we can collect into a string but that may be heavy. Since total output is ≤1e6, we can just print directly using printf/iostream and manage spaces. In C++ we can use a loop: bool first = true; for(int cur = head[t]; cur != -1; cur = nodes[cur].next) { if (!first) cout << ' '; cout << nodes[cur].val; first=false; } cout << '\n';
But note: This can be slow if we use endl (flushing). Use '\n'. For large output (1e6 numbers) it's okay.
But maybe we need to consider that printing each number individually with cout might be slower. However, total printed numbers 1e6, that's fine. Could also use write to buffer, but not necessary.
Now, for typ == 2: read s, t. Splice.
Be careful: The input indices are given as t, s in range [0, n-1]. The constraints say n ≤ 1000, so they are small.
Now, about reading input: q up to 500k, so we need fast input. Use scanf in C or cin with sync off. We'll use scanf for integers.
Now, check any edge cases: After splicing s into t, if t is non-empty, we set next[tail[t]] = head[s]. But we must ensure that tail[t] is a valid node index. It will be, because t is non-empty implies tail[t] != -1.
Also, after splicing, we set head[s]=tail[s]=-1, making s empty. That's fine.
Now, is there any scenario where we need to update something else? For example, if we have many splices and later we dump, the next pointers correctly chain all nodes.
One more nuance: When we splice, we need to ensure that we don't create cycles? Not possible because we are moving a list from s to the end of t, and s becomes empty, so we don't have multiple heads pointing to same nodes. That's fine.
Thus solution is straightforward.
But wait: There is a known problem with this approach: The problem is from JOI or something? Actually, this is a typical problem "list operations" from JOI 2014? I recall a problem "List" from AtCoder? Actually, there is a problem "List" from JOI 2014 Spring Camp? I'm not sure.
But let's double-check the constraints: n up to 1000, q up to 500k. The total number of elements printed ≤ 1e6. So dump is okay. But what about the total number of nodes? Up to q. So memory is okay.
Thus the singly linked list approach is efficient.
But there is a potential nuance: The problem statement says "dump(t): Print all elements in L_t." and "splice(s,t): Transfer elements of L_s to the end of L_t. L_s becomes empty." Nothing is said about order, but it's implied they keep order. So our method works.
Now, consider alternative: Using deque and splicing by moving all elements, but that would be O(size). So we avoid.
Thus we implement.
Now, we must also consider potential TLE due to pointer overhead? With 500k operations, each is O(1) except dump (bounded). So overall time is fine.
Now, I'll outline the code.
Implementation:
#include
#include
using namespace std;
struct Node {
int val;
int next;
Node(int v) : val(v), next(-1) {}
};
int main() {
int n, q;
scanf("%d %d", &n, &q);
code
vector<int> head(n, -1);
vector<int> tail(n, -1);
vector<Node> nodes;
nodes.reserve(q);
for (int i = 0; i < q; ++i) {
int typ;
scanf("%d", &typ);
if (typ == 0) {
int t, x;
scanf("%d %d", &t, &x);
int idx = nodes.size();
nodes.emplace_back(x);
if (head[t] == -1) {
head[t] = idx;
tail[t] = idx;
} else {
nodes[tail[t]].next = idx;
tail[t] = idx;
}
} else if (typ == 1) {
int t;
scanf("%d", &t);
// dump
int cur = head[t];
if (cur == -1) {
putchar('\n');
} else {
// print values
bool first = true;
while (cur != -1) {
if (first) first = false;
else putchar(' ');
printf("%d", nodes[cur].val);
cur = nodes[cur].next;
}
putchar('\n');
}
} else { // typ == 2
int s, t;
scanf("%d %d", &s, &t);
if (head[s] == -1) {
// should not happen per constraints, but just skip
continue;
}
if (head[t] == -1) {
head[t] = head[s];
tail[t] = tail[s];
} else {
nodes[tail[t]].next = head[s];
tail[t] = tail[s];
}
head[s] = tail[s] = -1;
}
}
return 0;
}
But note: when printing we used printf for each integer, and putchar for spaces and newline. That's fine.
Potential micro-optimizations: We could use write to stdout in a buffer, but 1e6 integers, each up to 10 digits, ~10MB output, acceptable.
We also need to consider that x can be negative, so printing with printf("%d") is okay.
Now, let's double-check input reading: typ is 0,1,2. For typ==0 we read t and x. For typ==1 we read t. For typ==2 we read s and t. There's no extra numbers.
Also, the problem states that for splice, L_s is not empty. So we could avoid the check.
Now, some might worry about integer overflow? No.
Now, one more nuance: After splicing, we set head[s] and tail[s] to -1. But what about nodes that were moved? They still have next pointers that point to the rest of the chain. That's fine.
Thus solution complete.
But there is a possible alternative: using union-find or list of list? But not needed.
Now, check performance: For each insert we push_back into vector, O(1) amortized. For each splice, O(1). For dump, O(k). Acceptable.
Now, test with given example.
Let's simulate code with sample input.
We'll mentally simulate.
Works.
Now, edge case: n=1? But insert and dump only for list 0. Splice would require s != t, so splice can't happen because only one list? Actually, if n=1, then s and t must be distinct, impossible, so maybe no splice queries for n=1. But our code would handle anyway.
Edge case: multiple splices that chain: Suppose we splice s into t, then later splice t into u, etc. Our code correctly concatenates.
Potential bug: When we splice s into t, and t is not empty, we set nodes[tail[t]].next = head[s]. But what if tail[t] is the same as head[s]? That would create a cycle? Not possible because s and t are different lists and s is non-empty; but after splicing, we clear head[s], but if s and t were previously linked? Could there be a scenario where some nodes from s are also part of t? That would mean the same node belongs to two lists, which can't happen because we always move entire lists and empty the source. There is no sharing of nodes. So it's fine.
Thus correct.
But wait, there is a nuance: What if we splice s into t, and later we splice t into s? For example, after first splice, s becomes empty, t contains elements. Then later, we insert into s some new elements, then we splice t into s. That's allowed because s != t and L_t non-empty. Then we attach t's list to the end of s's list. That's fine. Our code: if head[t] is not empty, we do if head[s] is empty? Actually, we handle whichever target. It works.
Now, consider performance of dump: we traverse from head[t] to tail[t] via next pointers. However, if we have performed many splices, the list might be extremely long (up to 500k). But as total printed elements is limited to 1e6, we will not dump that long list many times, but maybe once. So okay.
But if we have many dump operations on lists that are empty or short, it's fine.
Thus solution passes.
Now, I'll produce final answer with explanation and code.
But I'd like to add some more explanation about data structure: we use a linked list with head and tail pointers for each list, and nodes stored in an array.
We also note that we use -1 to denote null.
Now, final answer:
We'll provide a solution in C++.
Potential improvement: using fast I/O.
Implementation:
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
code
int n, q;
cin >> n >> q;
vector<int> head(n, -1), tail(n, -1);
struct Node { int val, next; };
vector<Node> nodes;
nodes.reserve(q);
while (q--) {
int typ;
cin >> typ;
if (typ == 0) {
int t, x;
cin >> t >> x;
int idx = nodes.size();
nodes.push_back({x, -1});
if (head[t] == -1) {
head[t] = tail[t] = idx;
} else {
nodes[tail[t]].next = idx;
tail[t] = idx;
}
} else if (typ == 1) {
int t;
cin >> t;
int cur = head[t];
if (cur == -1) {
cout << '\n';
} else {
while (cur != -1) {
cout << nodes[cur].val;
cur = nodes[cur].next;
if (cur != -1) cout << ' ';
}
cout << '\n';
}
} else { // typ == 2
int s, t;
cin >> s >> t;
if (head[s] == -1) continue; // not happening
if (head[t] == -1) {
head[t] = head[s];
tail[t] = tail[s];
} else {
nodes[tail[t]].next = head[s];
tail[t] = tail[s];
}
head[s] = tail[s] = -1;
}
}
return 0;
}
But note: using cin/cout with disabled sync is fine for 500k input lines. Could also use scanf/printf for safety.
We'll present with scanf/printf for faster.
Now, produce final answer.
But wait, I'm recalling a similar problem from JOI: "List" where they require splice to be done in O(1). Yes, this is that problem.
Thus we can finalize.
But to be thorough, let's test with a more complex scenario: n=2, q=...
We'll test manually:
Inserts: 0 0 1; 0 0 2; 2 0 1; dump 1; dump 0.
Should print "1 2" on dump 1? Let's see: after inserts: L0: 1->2; L1 empty. splice 0 to 1: head[1] empty so head[1]=head0, tail[1]=tail0; then L0 empty. dump1: 1 2; dump0: empty. Works.
Now, test if we insert after splice: After above, insert 0 0 3. L0: 3. Then splice 1 0? Actually, L1 non-empty, L0 has 3. splice 1 0: attach L1 to end of L0. L0: 3 then 1,2. dump0: 3 1 2. Works.
So fine.
Now, time complexity: O(q + total printed) = O(500k + 1e6) ~ 1.5e6 operations, well within limits.
Thus final solution.
Now, provide explanation: We'll describe the linked list structure, head and tail, node array, operations.
We'll also note that we use 0-indexing consistent with problem.
Now, produce final answer. We can solve the problem by maintaining each list as a singly linked list with head and tail pointers. All nodes are stored in a global array, each containing its value and the index of the next node. Insertion appends a new node to the end of the given list. Splice attaches the whole list s to the end of list t by linking the tail of t to the head of s and updating the tail, then making s empty. Dump traverses the list and prints all elements.
All operations are O(1) except dump, whose total cost is bounded by the total number of printed elements (≤ 1e6). This is efficient for the given limits.
cpp
#include <cstdio>
#include <vector>
using namespace std;
struct Node {
int val;
int next;
Node(int v) : val(v), next(-1) {}
};
int main() {
int n, q;
scanf("%d %d", &n, &q);
vector<int> head(n, -1), tail(n, -1);
vector<Node> nodes;
nodes.reserve(q); // at most q insertions
while (q--) {
int typ;
scanf("%d", &typ);
if (typ == 0) { // insert
int t, x;
scanf("%d %d", &t, &x);
int idx = nodes.size();
nodes.emplace_back(x);
if (head[t] == -1) {
head[t] = tail[t] = idx;
} else {
nodes[tail[t]].next = idx;
tail[t] = idx;
}
} else if (typ == 1) { // dump
int t;
scanf("%d", &t);
int cur = head[t];
if (cur == -1) {
putchar('\n');
} else {
bool first = true;
while (cur != -1) {
if (first) first = false;
else putchar(' ');
printf("%d", nodes[cur].val);
cur = nodes[cur].next;
}
putchar('\n');
}
} else { // splice, typ == 2
int s, t;
scanf("%d %d", &s, &t);
// according to constraints L_s is not empty
if (head[t] == -1) {
head[t] = head[s];
tail[t] = tail[s];
} else {
nodes[tail[t]].next = head[s];
tail[t] = tail[s];
}
head[s] = tail[s] = -1; // make L_s empty
}
}
return 0;
}