problems / 149

Alice's Swap Pairs

medium union-find strings sorting graphs 1000 ms · 256 MB

Alice's Swap Pairs

Bob wrote a word on a row of n letter tiles and handed it to Alice together with a list of m pairs of positions. Alice may pick any pair (a, b) from the list and swap the tiles at positions a and b. She may do this as many times as she likes, in any order, reusing pairs freely (or doing nothing at all). Alice wants to end up with the lexicographically smallest word possible. Help her find it.

Formally, you are given a string s of length n consisting of lowercase English letters and m pairs (a_i, b_i) of positions (1-indexed). In one operation you may choose any i and exchange the characters s[a_i] and s[b_i]. Among all strings obtainable by a finite sequence of operations (possibly empty), print the lexicographically smallest one.

Input

The first line contains two integers n and m (1 ≤ n ≤ 2·10^5, 0 ≤ m ≤ 2·10^5).

The second line contains the string s of exactly n lowercase English letters.

Each of the next m lines contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n). A pair may have a_i = b_i (swapping a tile with itself does nothing), and the same pair may appear several times.

Output

Print the lexicographically smallest string Alice can obtain.

Notes

In the first example, the pairs (1, 4) and (4, 2) let Alice move tiles freely among positions 1, 2 and 4 (for instance, swapping along (1, 4), then (4, 2), then (1, 4) again exchanges positions 1 and 2). Those positions hold d, c, a, so the best she can do is put a, c, d there in that order. Positions 3 and 5 are linked to each other, so they receive b and e.

In the second example there are no pairs, so the word cannot change.

Example 1

Input

5 3
dcbae
1 4
4 2
3 5

Output

acbde

Example 2

Input

4 0
baba

Output

baba

Hints · reveal one at a time if you're stuck

Hint 1

Treat each position as a node and each allowed pair as a link. Which letters can ever reach a given position, and does any swap ever move a letter out of its group of linked positions?

Hint 2

Group the positions with union-find. Within a group, the letters can be rearranged in any order, so think about what to do with each group's letters while scanning positions from left to right to make the string as small as possible.

report an issue Prefer your own editor? sooks prep 149 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.