We need to parse problem: We have permutation p of numbers 1..n. We have m pairs of positions (a_j, b_j). At each step we can choose a pair from the given positions and swap the numbers in those positions. We can apply swaps any number of times, possibly reusing pairs? Usually these problems: We have a graph where vertices are positions 1..n, edges are given pairs. Swapping along an edge, and we can perform any sequence of swaps. The set of reachable permutations are those that preserve the relative order within each connected component? Actually swaps allow us to rearrange numbers arbitrarily within each connected component because the swaps generate the full symmetric group on that component (since edges allow swapping any two? Not necessarily: if the graph is connected, we can generate any permutation of the vertices via swaps? In graph with nodes and edges that allow swapping elements, the reachable configurations are those where the multiset of values in each connected component is fixed, but we can permute them arbitrarily because swaps generate the full symmetric group on a connected graph? Wait: swapping along edges, we can move any element to any vertex if the graph is connected? Typically, if you have a graph where you can swap elements on adjacent vertices, then the group of reachable permutations is the whole set of permutations that map vertices to values, preserving the multiset within each connected component? Actually consider a graph with nodes, each node contains a number. You can swap numbers on nodes connected by an edge. This operation generates the permutation group that is the set of all permutations that are within each connected component? More precisely, the set of reachable configurations from initial configuration is: for each connected component, the set of values originally in that component can be arbitrarily permuted among the nodes of that component? I think yes, because the adjacent swaps generate the symmetric group on a connected graph. Is that always true? For an arbitrary connected graph, the group generated by transpositions corresponding to edges is the full symmetric group on the vertex set. Because any transposition can be expressed as a product of adjacent transpositions if the graph is connected? Actually need to check: The set of transpositions (i,j) for edges (i,j) generates the full symmetric group on the vertices if the graph is connected. Since any permutation can be written as product of transpositions, and any transposition (u,v) can be expressed as a sequence of edge transpositions along a path: (u, v) = (u, a1)(a1, a2)...(ak, v)... (in reverse). However, the product of transpositions along a path is not equal to a single transposition (u,v) but rather a conjugation? Let's recall: Swapping along adjacent edges: If we have a path u - a - b - v, can we swap u and v? We can move the value at u to v by a series of swaps: swap u-a, then a-b, then b-v, then b-a, then a-u? Actually we can perform a series of adjacent swaps to move an element to any position, and then similarly move others. The group generated by adjacent swaps on a connected graph is indeed the full symmetric group. Because the graph's edges generate the symmetric group as Coxeter generators? In bubble sort we use adjacent swaps on a line. On a tree, we can also generate any permutation by moving elements one by one. More formally, if the graph is connected, then the group of permutations achievable by composing swaps on edges is the whole symmetric group on that component. Proof: We can bring any element to any position by walking it along a path, swapping with the element currently there. This effectively moves that element to the target and shifts others along the path. By doing such moves, we can rearrange arbitrarily. So indeed, within a connected component, we can permute the numbers arbitrarily. Thus the reachable permutations are exactly those where for each connected component, the multiset of numbers in that component is fixed (i.e., the set of numbers initially occupying vertices in that component). So we can reorder numbers arbitrarily within each component.
Given that, we want to obtain lexicographically maximal permutation (largest possible lexicographically). Since we can arbitrarily permute numbers within each component, we want to assign the largest numbers to the smallest indices (positions) as much as possible, but subject to the constraint that numbers assigned to a component must belong to that component's set. So it's like: We have positions partitioned into components. For each component, we have a set of values (the numbers initially in that component). We can arrange them arbitrarily on the positions in that component. We want the lexicographically maximum overall permutation. Lexicographically maximum means we want the first position to be as large as possible, then second as large as possible given the first, etc.
This is a classic problem: given connected components and initial values, we can assign values to positions to maximize lex order. Typically we can process positions from 1 to n, and for each position, we want to assign the largest possible number that can be placed there, ensuring that the remaining numbers can still be assigned to the remaining positions respecting component constraints. This is akin to greedy assignment: For each component, we have a multiset of values. When we consider position i (which belongs to some component C), we need to decide which number from the component's multiset to place at i. The greedy is: at each step, choose the largest number from the component's multiset that does not prevent a valid assignment for the rest of positions. But we also must consider that if we take a number for this position, the rest of the positions in the component will get the remaining numbers. Since we can permute arbitrarily, the only constraint is that after assigning some number to this position, the remaining numbers must be assignable to the remaining positions in that component, but since we can permute arbitrarily, any ordering of the remaining numbers is fine. So for a component, the only thing that matters is the set of numbers currently left in that component. For position i, if its component C has some set of remaining numbers S, we need to pick the maximum possible value from S to put at i, but is there any global restriction? Since components are independent, picking a number from component C for position i only affects C's remaining numbers. There's no cross-component constraints because numbers cannot move between components. So indeed, for each position i in order, we can simply assign the largest remaining number from the component of i to that position. That yields lexicographically maximum permutation. But wait: Is that always valid? Let's test: Suppose we have two positions: positions 1 and 2 are in the same component, with numbers {1,2}. Then greedy: position1 picks largest remaining =2, then position2 gets 1 -> permutation [2,1] which is lex max (since the alternative is [1,2]). Good. Suppose positions 1 and 2 are in different components: component A contains position1, numbers {2}; component B contains position2, numbers {1}. Then at position1, largest from component A is 2, assign -> position1=2, then position2 gets 1 -> [2,1]. Could we get [1,2]? No, because number 2 cannot go to position2. So indeed greedy works. But wait: what about situation where we have component with multiple positions, and we might want to reserve a large number for a later position in the same component if that later position is earlier in lex order? Lex order is from position 1 to n. To maximize lex, we want the earliest positions as large as possible. So sacrificing a large number for later positions would not help lex order because later positions are considered only after earlier ones are fixed. So it's always optimal to put the largest available number at the earliest position of each component. However, careful: because components are independent, but the order of positions within a component is determined by the indices. So if we have a component that spans positions i1 < i2 < ... < ik. At position i1 (the smallest index), we want to put the largest number from the component's set, because it's the earliest unfilled position. Then at i2, we want to put the largest remaining, etc. That's clearly optimal. So the greedy algorithm: For each component, we have a multiset of its values. Sort these values descending. Then we assign to the positions in the component sorted ascending order (by index) the descending sorted values. That yields lexicographically maximum permutation. Indeed, we process positions in increasing order, but if we precompute component positions sorted, we can assign. So algorithm:
- Build DSU (disjoint set union) of n nodes (positions) with m edges (given pairs). Note m up to 10^6, n up to 10^6. DSU with path compression and union by size works.
- After building DSU, for each position i, find its root. For each component (root), we need to collect:
- list of positions in that component.
- list of values (p_i) in that component.
- Then for each component, sort positions ascending, sort values descending.
- Then assign for j=0..len-1: result[pos_j] = values_desc[j].
- Output result array.
Complexities: O(n log n) for sorting per component total (sum of component sizes). Since total elements across components is n, total sorting complexity O(n log n) if we sort each component individually, but we could also use global sorting? But each component needs to sort its positions and its values. Sum of sizes = n, but sorting each component individually yields sum of (size_i log size_i) which <= n log n because log is concave? Actually worst-case when one component of size n, it's n log n. If many components, sum of size_i log size_i <= n log n because size_i log size_i ≤ size_i log n, so total ≤ n log n. So O(n log n) is fine for n=10^6. However m up to 10^6, DSU operations O(α(n)).
But wait, m up to 10^6, but n also up to 10^6, memory: edges are not stored beyond DSU unions, we can process each edge and union. So reading edges and union.
Potential pitfalls: The input size large, need fast I/O. Use scanf or sys.stdin.buffer.
Thus answer: For each component, sort its positions ascending and values descending, then assign.
Implementation steps:
- Read n, m.
- Read permutation array p (1-indexed or 0-indexed). We'll store in list of ints size n.
- Initialize DSU parent array size n, and size or rank.
- Loop m times: read a, b (1-indexed). Convert to 0-index. Union(a-1, b-1).
- After unions, build dictionary (or list of lists) mapping root -> list of indices and list of values.
We can allocate vector of vectors? For n=10^6, using Python might be memory heavy if we use list of lists and append. But manageable: we have two lists: indices_by_root and values_by_root. Since we need to collect per component, we can create an array of length n for root mapping, then we can iterate i from 0 to n-1: root = find(i). Append i to list for that root; also append p[i] to values list.
But storing many small lists might be okay? However we need to later sort each component. In Python, using dictionary mapping root to list may have overhead. Better approach: After DSU, we can group indices by root using an array of vectors? In Python we can use list of lists: comps = [[] for _ in range(n)]? That would allocate n empty lists, which is memory heavy (each list overhead ~56 bytes, so 1e6 lists would be 56 MB, maybe too high? Actually Python list overhead is about 56 bytes per empty list, so 56 million bytes ~ 56 MB plus the array of references. That could be borderline but maybe okay? But also we have other arrays. However typical memory limit may be 256 MB. Let's compute: n=1e6, parent array (int) ~ 8 MB if using array('I') or list of ints? Python ints are 28 bytes each, so list of 1e6 ints is about 28 MB. Actually Python int objects are 28 bytes (on 64-bit) plus list references 8 bytes each? Actually list stores pointers to PyObject, each 8 bytes. So a list of n ints: the list itself occupies 8*n bytes for references (~8 MB), plus each int object ~28 bytes, total ~36 MB. That's a lot. Two such arrays (parent, size) would be 72 MB. So Python memory for n=1e6 is challenging but possible if we use more efficient structures like array module or use built-in list but with careful memory. However typical competitive programming in Python for 1e6 DSU often uses list for parent but it's okay if memory limit is 256 MB? Let's compute: parent: list of ints, each int object 28 bytes, but actually small integers are cached? No, Python caches small ints from -5 to 256, but for larger ints (up to 1e6), they are not cached, but each int is a separate object? Actually Python ints are objects. So parent list of size 1e6 would contain ints from 0..1e6-1, each is a separate int object? Actually integer literals up to 2**30 maybe are preallocated? Python might intern small ints, but numbers up to 256 are cached. For larger numbers, they are not cached, but when we assign i to parent[i] = i, that creates a new int object? Actually the integer i already exists as an object (since it's from range), but it might be shared? In CPython, integers are immutable and sometimes reused but not guaranteed beyond small range. For numbers like 500000, it's a new int each time? Actually if we have the same integer value from the same source, it may refer to the same object due to interning? Not for arbitrary ints. Usually each occurrence of an integer literal in code results in a constant, but when we assign from range, each number is produced as an int object; they are likely distinct objects? However Python may reuse small ints via caching only for a limited range. So for large ints, each time we have a different object? In CPython, integer objects are created for each value when needed, but if we have the same value multiple times, they might be the same object due to small integer caching? Actually small integer caching only caches from -5 to 256. For larger values, each evaluation of that value creates a new int object, but if we have the same constant value in code, the compiler might reuse it? For example, a = 1000; b = 1000; might be same object due to constant folding? In CPython, the interpreter may reuse immutable objects for constants in the same code block, but when we generate ints via range, each iteration yields a new int? Actually range yields ints each time; they are not cached, so they are distinct objects. So parent list would contain 1e6 distinct int objects, each 28 bytes, plus list references 8 bytes each -> ~36 MB. That's for parent. Another list for size (or rank) maybe also ints, another 36 MB. That's 72 MB. Then we have p array (list of ints) 36 MB. That's 108 MB. Then we need arrays for grouping: We could avoid storing size if we use parent only and union by size but we need size for union by size, so need one more array (size). Could we compress? Possibly use array('I') from array module to store 4-byte unsigned ints. That would be 4 MB per array. Use that to save memory. But DSU with array('I') operations may be slower due to conversion? But acceptable. Or use list of ints but rely on memory? 108 MB maybe ok if memory limit is 256 MB, plus overhead for grouping. But grouping using list of lists: we could avoid storing separate comps lists by using an approach: after DSU, we assign each node a component ID (root). Then we can sort nodes by root, but that would involve sorting n items by root, which is O(n log n) but could be done with bucket sort because root values are indices? Actually root values are in 0..n-1. We could create an array of vectors using "list" but we need to store indices and values per component. We could use two arrays: comp_indices = [[] for _ in range(n)], but that would allocate n empty lists (each empty list overhead maybe 56 bytes) -> 56 MB, which pushes total over. However we can avoid allocating n lists by using a dictionary: only store for roots that actually exist. After DSU, we can iterate over all i, find root, and then append to list in dict: dict.setdefault(root, []).append(i). But dict of up to n entries if many components, but average maybe less. However each component will have at least 1 element. Worst-case if each node is its own component, there will be n entries in dict. That's again n key-value pairs, each key is int, each value is a list object. Overhead for dict entry: about 72 bytes? Actually Python dict entry is around 72 bytes? Might be too high. So n=1e6 separate components would be huge memory > 200 MB.
Thus we need a memory-efficient approach in Python for 1e6. We can solve without per-component dynamic lists: We can first compute roots and then produce an array of (root, index) pairs, then sort this array by root, effectively grouping nodes by root. Then we can iterate over groups and within each group, we have indices sorted (since we will sort by root, but indices within group are in the order they appear in the sorted array; we can also sort by index within each group later). Then we also need the values for each index. So we can create an array of tuples (root, index, value). Then sort by root (and maybe index?). Actually we want: For each component, we need to output the values in descending order assigned to positions in ascending order. So we can:
- For each i in 0..n-1, compute root_i = find(i).
- Create list "items" of (root_i, i, p[i]).
- Sort items by root_i (primary), and then by i? Not exactly. We want to group by root. Within each group, we need the indices in ascending order, and we need to assign descending sorted values to those indices. So we can sort the whole array by root. Then, for each group (contiguous after sort), we have a list of (i, p[i]) in some order. But the order of items in the group after sort by root is not necessarily sorted by i; it's whatever order they were added. But we can sort the group separately by i, or we can sort the entire items by (root, i). That would give groups sorted by root and within each group sorted by i. So we can sort items by (root, i). That yields for each component, the indices in increasing order.
Now we also need the values of that component sorted in descending order. So we can also collect for each component the values list. But we can avoid per-component list by also sorting values? Actually we can, for each component, extract the values from the items (since they are in the same group) and sort them descending. But we need to assign them in order to indices. So after we have the groups sorted by root and index, we can for each component, extract the values (p[i] for i in component) into a list, sort descending, then assign to the indices (which are sorted ascending) in order. But we still need to store the values per component temporarily. Since we process groups sequentially, we can store the list of values for that group, sort it, and then assign. The total size of all values is n, and we can free each list after processing. So we can process without storing all groups simultaneously. But we need to be able to iterate over items in group order. Sorting items by (root, i) gives a list of n tuples. That list occupies memory: each tuple (3 ints) takes maybe 72 bytes? That would be huge (72 MB * 3?). Actually a tuple of 3 ints: overhead of tuple (~56 bytes) plus three pointers to int objects (8 each) = 80 bytes, plus the int objects themselves which are shared? The ints are already stored elsewhere? In the tuple we store references to the same int objects that exist in p and i? But i is from range, we have int objects for each i? Actually each i is an int from the loop; if we generate a new int each iteration, we create many int objects. So memory would blow up. So we need a more efficient representation.
Alternative: Use arrays of ints for root, index, value. We could sort based on root and index using Python's sort with key that returns a tuple? That still requires constructing tuple for each element? Possibly we can use numpy? Not allowed.
We need to find a more memory-friendly approach.
Observation: After DSU, we know the root for each node. We can assign each component an ID (maybe the root itself). We need to group nodes by root. We can do bucket sort: Since roots are numbers in [0, n-1], we can compute for each root the list of indices using an array of vectors but we need to avoid overhead of Python list per root. Instead we can use a single array to store all indices contiguously with a head pointer per component using the "adjacency list" technique: we can compute the size of each component first, then allocate a flat array of length n for indices, and an array of offsets. Similarly for values.
Plan:
- Step 1: DSU as before, using arrays of ints (maybe array('I') or list of int) but we need find. Use list of ints for parent (size n) and maybe size (list of int). Given memory, list of ints for parent and size: each list of n ints uses ~28 bytes per int? Actually each int object 28 bytes, plus list reference 8 bytes = 36 bytes per element? Wait: The list stores pointers to PyObject. The int objects themselves are separate. So for parent list: we have n entries in list (8 bytes each) = 8n bytes for references. The int objects: each int is a Python object with overhead ~28 bytes. However many of those ints might be small and cached? For numbers 0..n-1, they are within the range of cached small ints? CPython caches -5 to 256. For numbers >256, they are not cached. So for n up to 1e6, most numbers are >256, so they would be new ints. But when we set parent[i] = i, we are assigning the same integer object i from the loop. In Python, the loop variable i from range yields a new int each iteration? Actually range yields ints, each int is a new object? In CPython, range iterator returns the same int object? I recall that in CPython, range yields ints one after another, but it reuses the same int object? Actually Python integers are immutable. The range iterator increments a C long and creates a new PyLong object each iteration? I think it creates a new int each time, but maybe it caches? Not sure. Let's test mental: for i in range(1000000): a = i; b = i; Here, each iteration, i is an int object; the same object may be reused? Actually ints are immutable, so each iteration the variable i is assigned a new int object. But the int object for 0,1,2,... may be created only once and reused? I think Python creates new int objects for each arithmetic operation, but for small ints it uses preallocated ones. For large ints, it may allocate new ones each time they appear. However, the range implementation might allocate a new int each time it yields a value, but it might use a cached pool? I'm not 100% sure. But typical memory for list of ints of size 1e6 in Python is around 28 MB for the ints plus 8 MB for references = 36 MB, as often measured. So parent list ~36 MB, size list ~36 MB, p list ~36 MB = 108 MB. That's acceptable if memory limit is 256 MB. Additionally we need other structures: We'll also need an array for root per node (we already have parent; we could reuse parent after path compression? But we need to call find for each node after unions; we could do that and store root in an array, maybe separate array "comp_id" of n ints. That would be another 36 MB -> 144 MB. Could be borderline but maybe still okay.
But we need to group nodes by root efficiently. One method: Use an array of heads for each component? But components are many maybe. Instead we can avoid storing separate grouping arrays by using sorting with a key that is root, but without storing tuples. We can create an array of indices 0..n-1, and sort this array using a key function that returns root of index. That way we have an array of n ints (the indices) sorted by component root. Then within each component, we need to sort indices? Actually the sorting by root will put all indices of the same root together, but not necessarily sorted by index within component. We could sort by (root, index) by using a key that returns (root, index). But then we need to call root function for each comparison, which would be O(n log n) with many find calls, but find is O(α) but each comparison would call key function possibly multiple times? Python's sort computes the key once per element and stores it. So we can create a list of (root, index) pairs? That returns to tuple memory. But we can compute a single integer key that encodes root and index: e.g., key = root * n + index. Since root in [0, n-1], that key is up to n^2 ~ 1e12, fits in Python int. So we can create a list of indices, and then sort them using a key that returns root * n + index. That key is a Python int (which is an object) but it's computed on the fly and stored in the sort's decorate-sort-undecorate? Actually Python's sort with key parameter computes the key for each element and stores them in a separate list? The timsort algorithm computes keys and keeps them alongside the items? I think it computes key for each element once and stores them in an array of "keys" of same length as the list. So that would allocate another array of n Python objects (the keys). That would be additional memory (n ints, ~28 MB each? Actually keys are ints, each maybe 28 bytes). So extra ~28 MB plus references? Actually the list of keys itself is a list of n pointers to int objects, each int object ~28 bytes. So total for keys: 8n for references + 28n for ints = 36n ~ 36 MB. So total memory: parent (36), size (36), p (36), indices list (36) (list of ints, each element an index integer), keys (36) ~ 180 MB, plus overhead for list objects themselves (each list overhead ~56 bytes). Still maybe okay. But we also need an output array (result) of n ints: another 36 MB. Total > 200 MB. Could be close but maybe within 256 MB.
But we might reduce memory by using array module for some structures: parent and size and p can be arrays of type 'I' (unsigned int) or 'L' (unsigned long). That would store 4 bytes per element, much smaller. For p and result, we can use array('I'). For parent and size, we can use array('I') as well. However DSU operations need random access and assignment, which array supports. But find with recursion might be slower; we can implement iterative find.
But using array('I') for parent and size would reduce memory dramatically: 4 MB each for n=1e6. For p and result similarly 4 MB each. So total for these four arrays: 16 MB. That's great. Now we need to group nodes. For grouping, we could use the following: after DSU, compute root for each node and store in an array "root_of" of ints (4 MB). Then we need to group indices by root. We can use a counting sort approach: Since root values are in 0..n-1 but not all used, we can compute the count of each root (for only those that are roots). But we need to know which roots are actual component representatives. Let's do:
- After all unions, for each i in 0..n-1: r = find(i) (using DSU with path compression). We'll store r in an array comp_id[i] (maybe reuse parent? But after path compression, parent[i] is root, but we still need parent for DSU? After unions we are done, so we can use parent array to store root after find for all i? Actually we can compress paths and then parent[i] will be the root, so we can treat that as component id. So we can avoid separate comp_id array; we can just use parent after full path compression. So we can have parent array (already 4 MB) that now stores root for each node (after we call find for each i). That's fine.
Now we need to group indices by root. We can compute for each root the list of indices. To avoid many small list objects, we can use two arrays: "start" and "next" like adjacency list representation. This is a typical technique: For each node i, we want to link nodes belonging to the same root. We can create an array "head" of size n, initialized to -1, and an array "next" of size n. For each node i, root r = parent[i]. We'll add i to the list of r: next[i] = head[r]; head[r] = i. This constructs a linked list per root using arrays. However head is of size n (maybe many entries not used). head is array of ints (4 MB). next is array of ints (4 MB). That's acceptable. But note: we need to traverse each list later, and also need to sort values within each component. We can traverse each component's list to collect its indices and values. Since we'll need to sort values descending and indices ascending, we need to store the list of indices for each component. Using linked list we can collect them into a Python list temporarily when processing each component. But that would create many Python lists? Not necessarily: we can process each root that has a list, we traverse the linked list to collect all indices into a temporary Python list. The total size of all these temporary lists across processing will be O(n) but they are created and freed one by one; maximum memory at any time is the size of the largest component's list plus some overhead. That's okay. However, for each component, we need to sort its indices and values. But we need indices sorted ascending. The linked list order is arbitrary (order of insertion). We could collect them into a Python list and then sort it. That's fine.
But we also need the values for each component. We have p array (array('I')). So while traversing the list, we can collect indices, then we can get the values from p and sort them descending.
Implementation plan using arrays:
- Use sys.stdin.buffer.read() to read all ints.
- n, m = first two ints.
- Read p: list of n ints (maybe store as array('I') after reading).
- Initialize DSU: parent = array('I', range(n)) or list of ints? Actually array('I') can be initialized with range: array('I', range(n)). That creates array of unsigned ints. For DSU, we need to be able to assign parent. That's fine. Also size = array('I', [1])*n? Actually we need size for union by size. We'll create size = array('I', [1])*n? But array multiplication works: array('I', [1])*n gives array of length n with ones. However careful: 'I' is unsigned int (4 bytes). Max n = 1e6, fits.
But Python's array('I') does not support multiplication with a list? Actually array('I', [1])*n replicates the array n times, so yes.
-
For each of m edges: read a,b (1-indexed). Convert to 0-index: a-1, b-1. Union them.
Union function: find roots; if different, attach smaller size to larger. Use path compression in find.
Find function: while parent[x] != x: parent[x] = parent[parent[x]]? Or iterative with path compression: we can implement recursive? Recursion depth may be large, so iterative.
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
Or full path compression: use a stack. But simpler: while parent[x] != x: path.append(x); x = parent[x]; then for i in path: parent[i]=x. That's okay.
Since we will call find many times (for each union (2 per union) and after unions for each node (n times)), we need efficient.
-
After all unions, we need to ensure all nodes have parent as root (path compressed). We'll call find(i) for each i from 0 to n-1 and update parent[i] directly. So after this, parent[i] holds the root.
-
Build component lists using head and next arrays.
head = array('i', [-1])*n? But array('i') is signed int; we need to store indices, can use 'I' as well but -1 not representable? We can use 'i' for signed. Or we could use a separate array of ints with sentinel -1; for unsigned we could use a special value like n (outside range) to indicate null. Simpler: use Python list for head and next? But we want to save memory. Let's compute memory: head and next each n ints; if using array('I'), we can represent null as n (since indices 0..n-1). So we can set head[r] = n for empty (since n is not a valid index). That works. But we need to iterate later: for i in range(n): if head[i] != n: process. That's fine. However we need to store indices from 0..n-1. So sentinel n works.
So:
head = array('I', [n]) * n # all n (sentinel)
nxt = array('I', [0]) * n # placeholder, will be overwritten
For i in range(n):
r = parent[i]
nxt[i] = head[r]
head[r] = i
This builds linked lists: for each root r, head[r] points to first node i, and each node i has nxt[i] linking to next.
Note: We must ensure parent[i] is the root after find.
-
Now we need to produce result array res of length n (array('I')).
For each r in range(n):
if head[r] != n: # has component
# traverse list to collect indices
indices = []
# also collect values? We'll collect indices first then get values.
cur = head[r]
while cur != n:
indices.append(cur)
cur = nxt[cur]
# Now indices list has all positions in this component, but order arbitrary (the order we added, which is from i=n-1 down to 0 because we iterated i from 0 to n-1? Actually we iterated i from 0 to n-1, and for each i we prepend to list: nxt[i] = head[r]; head[r] = i. So order will be from last i (n-1) to first (0) for each root. So indices will be in decreasing order of i. Not sorted ascending.
# We need indices sorted ascending to assign largest values to smallest positions.
# So we sort indices ascending.
indices.sort()
# Get values for these indices from p
vals = [p[i] for i in indices]
# Sort vals descending
vals.sort(reverse=True)
# Assign to res
for idx, val in zip(indices, vals):
res[idx] = val
Potential issues: The linked list traversal uses while loop with cur != n. That's fine.
Memory: parent (4 MB), size (4 MB), p (4 MB), res (4 MB), head (4 MB), nxt (4 MB). That's 24 MB. Plus reading input (maybe we read all ints into a list) but we parse from bytes. So well under 256 MB.
But we need to be careful about array types: In Python, array('I') stores unsigned int (4 bytes). But n up to 10^6, so values up to 10^6 fit. p contains numbers from 1 to n, so fits. For size, union by size: max size can be up to n, which fits. For head sentinel we use n (which is up to 1e6) fits. For nxt, indices up to n-1 fit.
One subtlety: array('I') doesn't support negative numbers, so sentinel must be >=0. Using n works.
Implementation details:
- We'll read all input using sys.stdin.buffer.read().split() to get tokens as bytes, then map to int. That's fast but creates list of bytes strings of length (n+m2+2) up to 3e6, which might be memory heavy (each token as bytes object). But still okay? For 3e6 tokens, each token small (maybe up to 7 bytes), overhead of Python objects is large. 3e6 objects might be too much memory. Better to read line by line and parse ints? But reading all and splitting might be okay if memory limit is 256 MB? 3e6 objects could be huge (each bytes object ~33 bytes plus list overhead). That could be ~100 MB. To be safe, we can use a faster generator that yields ints from the buffer without creating all tokens. We can use map(int, sys.stdin.buffer.read().split()) which creates a list of ints? Actually map returns iterator, but then we convert to list? We need to get all ints. For n up to 1e6, m up to 1e6, total numbers = n + 2m + 2 ≈ 3e6. If we do data = list(map(int, sys.stdin.buffer.read().split())), that creates a list of 3e6 Python ints, each 28 bytes -> 84 MB. That's okay? Plus overhead for list (8*3e6=24 MB) -> total ~108 MB. That's not trivial but might be okay. But we also have other arrays. 108+24=132 MB, still okay. But we have to store p, etc. p we would store as array('I') using data slice. So maybe we can avoid storing all ints as Python ints? We can read line by line using sys.stdin.buffer.readline() and parse ints using split, but that also creates temporary lists. However overall memory may be manageable. Let's design to be safe: Use a fast int reader that yields ints one by one without storing all at once. For example:
def ints():
for num in sys.stdin.buffer.read().split():
yield int(num)
Then we can consume the generator to get n,m etc. But we still need to process many ints. This way we don't store all ints in a list; we just iterate over the split result which gives a list? Actually sys.stdin.buffer.read().split() returns a list of bytes, so that list is created. So that still creates a list of tokens (bytes). That's many bytes objects. Might be memory heavy.
Alternative: Use sys.stdin.buffer.readinto? Not.
Better: Use a custom fast input that reads bytes and parses ints on the fly without creating a list of all tokens. For example, define:
import sys
def readints():
data = sys.stdin.buffer.read()
num = 0
sign = 1
in_num = False
for c in data:
if c >= 48 and c <= 57:
num = num * 10 + (c - 48)
in_num = True
else:
if in_num:
yield sign * num
num = 0
sign = 1
in_num = False
if c == 45: # '-'
sign = -1
if in_num:
yield sign * num
But all numbers are positive so we can ignore sign.
This generator yields ints one by one without creating a big list of tokens. This is efficient.
So we will use that.
Now DSU implementation using arrays.
But Python's array('I') does not support some operations like list comprehension? It does. We'll create parent = array('I', range(n)). For range, range returns iterator, array('I', range(n)) will create array of n ints. That is okay. For size = array('I', [1])*n, but this replicates array. However [1]*n creates list of n ints, but we can do array('I', [1])*n. Let's test: from array import array; a = array('I', [1])*n; This works: it creates array of n copies of 1. Good.
But for head sentinel n, we can do array('I', [n])*n. Similarly nxt = array('I', [0])*n.
Now DSU find:
def find(x):
# path compression iterative
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
But careful: This version compresses partially. We can also use recursion with memoization? We'll do while loop with path compression:
def find(x):
# find root with path halving
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
That works.
Union:
def union(a,b):
ra = find(a)
rb = find(b)
if ra == rb:
return
if size[ra] < size[rb]:
ra, rb = rb, ra
parent[rb] = ra
size[ra] += size[rb]
Now after all unions, we need to call find on each element to flatten. We'll do for i in range(n): parent[i] = find(i). This updates parent to root.
Now build head and nxt.
head = array('I', [n])*n
nxt = array('I', [0])*n
for i in range(n):
r = parent[i]
nxt[i] = head[r]
head[r] = i
Now process components:
res = array('I', [0])*n # to be filled
for r in range(n):
if head[r] != n:
# collect indices
indices = []
cur = head[r]
while cur != n:
indices.append(cur)
cur = nxt[cur]
# now indices length = size of component
indices.sort()
# get values
vals = [p[i] for i in indices]
vals.sort(reverse=True)
for idx, val in zip(indices, vals):
res[idx] = val
But there is a nuance: The component root r might have head[r] as a linked list; but what if the component root is not the representative we used? In DSU, after path compression, parent[i] for all i is the root. So for each root r, head[r] is defined. However, after path compression, some roots may not have any element? Actually every i has a root r, so r will appear as root for at least itself. So head[r] is set for every root that is the representative of at least one node. So it's fine.
Complexity: O(n log n + m α(n)).
But note: Sorting vals and indices per component may cause total O(n log n). However we can avoid sorting indices by using the fact that indices can be collected in ascending order if we iterate i from 0 to n-1 and append to component list using tail insertion? If we want indices naturally sorted, we could for each component, store a list and then sort later. Sorting indices is O(size log size). That's acceptable. But we can also store indices in a list and then sort. Sorting may dominate but total O(n log n) with n=1e6, log n ~ 20, 20 million operations, Python might be okay with efficient sort (timsort) and if components are many small ones, overhead might be more but still okay. Could be borderline but likely fine.
But we might be able to avoid sorting indices by using the following: Since we need to assign largest values to smallest indices, we can simply for each component, get the list of indices (any order), sort them ascending, and sort values descending. That's fine.
Alternatively, we could avoid sorting indices if we collect indices in increasing order by iterating i from 0 to n-1 and appending to component's list in order. In linked list we prepend, so order is reversed. Instead, we could implement a vector per component using dynamic arrays? But we wanted to avoid many small lists. However we could build the component lists using an array of vectors by first counting sizes, then allocating a flat array, and then filling indices in order. That would allow us to have indices already sorted if we fill them in increasing i order. Let's see: We can first compute for each root the count of nodes, and also compute prefix sums to allocate offsets. Then we can make a pass to put each node i into its component's segment at the appropriate position, but we need to keep order. If we process i from 0 to n-1 and place i into the component's segment at the next free slot, then the indices within each component will be in increasing order naturally because we process i in increasing order and append to the component's list. So that would give sorted indices without extra sort. This approach uses additional arrays but avoids sorting indices.
Let's design that:
-
After DSU, we have parent array with roots.
-
Compute component sizes: size_comp[root] = number of nodes. We can reuse the size array from DSU? Actually DSU size array currently stores sizes of sets only for representatives? After unions, size array for non-roots might be outdated. But we can compute counts by scanning: cnt = array('I', [0])*n? But we want only for roots. We can allocate an array comp_size of length n zeroed. Then for i in range(n): r = parent[i]; comp_size[r] += 1. This gives size for each root.
-
Then compute start offsets: We can create an array start of length n (maybe only for roots that have non-zero count). But we need to map root to an index in a flat array. Since root values are from 0..n-1 but not all are used, we can just compute prefix sum over all indices 0..n-1 based on comp_size. But comp_size for non-roots is 0, so that's okay. However we need to compute exclusive prefix sums. Let's compute prefix sums in a new array offset of length n+1 maybe. But we need to store for each root the starting index in the flat array where its nodes will be placed. So we can compute:
offset = array('I', [0]) * (n+1) # but we can compute in-place.
total = 0
for r in range(n):
offset[r] = total
total += comp_size[r]
Now offset[r] is the start index for component with root r in the flat array. Additionally we need a current pointer array cur = offset.copy() to fill.
-
Then allocate a flat array comp_indices of length n (type 'I') to store indices (positions) of nodes. Also we need comp_values similarly? We'll just need indices, but we also need values. We can fill indices: for i in range(n): r = parent[i]; pos = cur[r]; comp_indices[pos] = i; cur[r] += 1.
-
After this, for each component root r, the indices are stored in comp_indices[offset[r]:offset[r]+comp_size[r]] and they are in increasing order because we processed i from 0 to n-1. Since we fill in order of i, the indices are sorted ascending.
-
Next, we need to assign the values. For each component root r, we need to take its values (p[i] for i in its indices) and sort them descending. Then assign to the indices in order.
We could also create a flat array for values: For each component, we could extract the values into a list, sort descending, then assign. We can do this without creating many small lists: For each component, we can get slice of comp_indices (the indices for that component) and also gather the corresponding p values into a temporary list (or we could copy values into a local list and sort). Since we have the flat array of indices, we can for each r with size>0:
start = offset[r]
end = start + comp_size[r]
get list of indices: indices = comp_indices[start:end] # this creates a new list? Slicing an array returns a new array? Actually array slicing returns a new array? It returns a new array object containing the slice. That's okay but it will allocate memory for that slice. However total memory for all slices would be O(n) but not simultaneously because we process one at a time and the slice array will be freed after use. But slicing an array of length n and size s creates a new array of s elements; that's fine. However we also need values: we can extract values for those indices: vals = [p[i] for i in indices] which creates a list of ints (Python ints). That's okay as temporary.
Then sort vals descending.
Then assign: for idx, val in zip(indices, vals): res[idx] = val.
But note: comp_indices is an array of unsigned ints. Slicing it yields a new array, but we can iterate over it without converting to list? We can simply iterate from start to end and get indices directly from comp_indices. That avoids creating a slice array? Actually we can just loop over range(start, end) and get index = comp_indices[k]. Then we can collect the values. That's simpler and uses less memory.
So algorithm:
-
After DSU and flattening, compute comp_size array (size n) initialized to 0.
-
For i in 0..n-1: r = parent[i]; comp_size[r] += 1
-
Compute offset array of length n (or n+1) where offset[r] = cumulative sum before r.
total = 0
offset = array('I', [0]) * n # but we need to store for each r
for r in range(n):
offset[r] = total
total += comp_size[r]
-
Now we also need a cur array to fill; we can use another array cur = array('I', offset) (copy) or just use a separate array of same length.
-
comp_indices = array('I', [0]) * n
-
For i in range(n):
r = parent[i]
pos = cur[r]
comp_indices[pos] = i
cur[r] += 1
-
Now for each r where comp_size[r] > 0:
start = offset[r]
end = start + comp_size[r]
# gather values:
vals = [p[comp_indices[pos]] for pos in range(start, end)] # this creates a list
vals.sort(reverse=True)
# assign
for pos in range(start, end):
idx = comp_indices[pos]
res[idx] = vals[pos - start] # because vals sorted descending
But note: In the assignment, we need to match sorted values to indices in order (indices are ascending). So we can simply assign as above.
This method sorts the values per component. The total sorting complexity is sum over components of size_i log size_i, same as before. However we avoided sorting indices. That may give some speed improvement.
Now we have to be careful: comp_size and offset arrays are of size n. That's additional 8 MB each if using 'I' (4 bytes). So total arrays: parent (4), size (4), p (4), res (4), comp_size (4), offset (4), cur (4), comp_indices (4), and maybe head and nxt not needed. That's 8 arrays * 4 MB = 32 MB. Plus overhead for Python objects: array objects themselves are small. So memory is fine.
But we also need to store edges? We process them on the fly, no storage.
Now DSU: we have parent and size arrays of type 'I'. But we need to update size during union, which may exceed 2^32? n up to 1e6, fits. So unsigned int is fine.
Now implement DSU find with array('I'): Since array elements are accessed via indexing, it's fine.
Potential issue: In Python, array('I') returns a mutable sequence with elements as Python ints? Actually when you access an element of array('I'), you get a Python int. So it's fine.
Now about reading input: We'll implement a fast integer generator to read all bytes and yield ints one by one. That function should be efficient.
We'll use:
def read_ints():
import sys
data = sys.stdin.buffer.read()
num = 0
for c in data:
if 48 <= c <= 57:
num = num * 10 + (c - 48)
else:
yield num
num = 0
yield num
But careful: There may be multiple numbers separated by spaces or newlines. The last number may not have a delimiter, so we need to yield after loop if num>0 or if we ended with a number. Also there may be negative numbers? No.
But note: c is an int from bytes iteration, so 48 <= c <=57 works.
But this generator yields numbers as we go, but it will also yield 0 for consecutive delimiters? Because if we have two delimiters, after first delimiter we yield num (which might be 0 if we haven't accumulated any digits), then reset to 0, then next delimiter yields 0 again. That would produce extra zeros. To avoid that, we need to track if we are inside a number. Let's do:
def ints():
import sys
data = sys.stdin.buffer.read()
num = 0
in_num = False
for c in data:
if 48 <= c <= 57:
num = num * 10 + (c - 48)
in_num = True
else:
if in_num:
yield num
num = 0
in_num = False
if in_num:
yield num
Now we can use it as:
it = ints()
n = next(it); m = next(it)
p = array('I', [next(it) for _ in range(n)])
Then for _ in range(m): a = next(it); b = next(it); union(a-1, b-1)
But caution: a and b are 1-indexed from input, convert to 0-index.
Now the DSU functions need to access parent and size arrays, which we'll define as arrays.
Now about recursion depth: no recursion.
Now about time: For each union, we do two finds. With path compression and union by size, effectively O(α(n)). For up to 1e6 operations, okay.
After unions, we need to compress paths for all nodes. We'll do for i in range(n): parent[i] = find(i). That's n finds.
Now compute comp_size: for i in range(n): r = parent[i]; comp_size[r] += 1.
Now compute offsets: We need to compute prefix sum. For that we need an array offset of length n. We'll compute:
offset = array('I', [0]) * n
total = 0
for r in range(n):
offset[r] = total
total += comp_size[r]
Now cur = array('I', offset) copy? Actually we need to modify cur while filling comp_indices. If we do cur = array('I', offset) (copy), that's fine.
But we need to be careful that offset[r] might be used later as start positions for each component. So we need to keep offset unchanged. So we copy.
Now comp_indices = array('I', [0]) * n
for i in range(n):
r = parent[i]
pos = cur[r]
comp_indices[pos] = i
cur[r] = pos + 1 # increment
Now processing components: For r in range(n):
sz = comp_size[r]
if sz == 0: continue
start = offset[r]
# collect values into a list
# we can do: vals = [p[comp_indices[start + j]] for j in range(sz)]
# but this creates Python ints; fine.
# Then sort descending.
# Then assign.
But we can maybe avoid creating vals list by using p as array and extracting values; sorting requires list. So we create list of size sz