Problem:
Score : 600 points

Problem Statement

You are given a forest with N vertices and M edges. The vertices are numbered 0 through N-1.
The edges are given in the format (x_i,y_i), which means that Vertex x_i and y_i are connected by an edge.

Each vertex i has a value a_i.
You want to add edges in the given forest so that the forest becomes connected.
To add an edge, you choose two different vertices i and j, then span an edge between i and j.
This operation costs a_i + a_j dollars, and afterward neither Vertex i nor j can be selected again.

Find the minimum total cost required to make the forest connected, or print Impossible if it is impossible.

Constraints

1 ≤ N ≤ 100,000

0 ≤ M ≤ N-1

1 ≤ a_i ≤ 10^9

0 ≤ x_i,y_i ≤ N-1

The given graph is a forest.

All input values are integers.

Input

Input is given from Standard Input in the following format:

N M
a_0 a_1 .. a_{N-1}
x_1 y_1
x_2 y_2
:
x_M y_M

Output

Print the minimum total cost required to make the forest connected, or print Impossible if it is impossible.

Sample Input 1

7 5
1 2 3 4 5 6 7
3 0
4 0
1 2
1 3
5 6

Sample Output 1

7

If we connect vertices 0 and 5, the graph becomes connected, for the cost of 1 + 6 = 7 dollars.

Sample Input 2

5 0
3 1 4 1 5

Sample Output 2

Impossible

We can't make the graph connected.

Sample Input 3

1 0
5

Sample Output 3

0

The graph is already connected, so we do not need to add any edges.

Solution in C# (Mono 4.6.2.0) (judge verdict: Runtime Error)

using System;
using System.Collections.Generic;

public class Program
{
    private int N, M;
    private int[] A;

    public void Solve()
    {
        var sc = new Scanner();
        N = sc.NextInt();
        M = sc.NextInt();
        A = sc.IntArray();

        var uf = new UnionFind(N);

        for (int i = 0; i < M; i++)
        {
            int x = sc.NextInt();
            int y = sc.NextInt();
            uf.Union(x, y);
        }

        var map = new Dictionary<int, List<int>>();

        for (int i = 0; i < N; i++)
        {
            int root = uf.Find(i);
            List<int> o;
            if (!map.TryGetValue(root, out o))
            {
                map[root] = new List<int>();
            }

            map[root].Add(i);
        }

        var pq = new PriorityQueue<PriorityQueueEX<int>>((a, b) => a.Peek().CompareTo(b.Peek()));
        foreach (KeyValuePair<int, List<int>> keyValuePair in map)
        {
            var pqex = new PriorityQueueEX<int>();
            foreach (int i in keyValuePair.Value)
            {
                pqex.Enqueue(A[i]);
            }
            pq.Enqueue(pqex);
        }

        long ans = 0;
        for (int i = 0; i < N - 1 - M; i++)
        {
            if (pq.Count < 2)
            {
                Console.WriteLine("Impossible");
                return;
            }

            var a = pq.Dequeue();
            var b = pq.Dequeue();
            ans += a.Dequeue() + b.Dequeue();
            var p = a + b;
            //Console.WriteLine(p.Count);
            if (p.Any())
                pq.Enqueue(a + b);
        }

        Console.WriteLine(ans);
    }

    public static void Main(string[] args)
    {
        new Program().Solve();
    }
}

class Scanner
{
    public Scanner()
    {
        _pos = 0;
        _line = new string[0];
    }

    const char Separator = ' ';
    private int _pos;
    private string[] _line;

    #region スペース区切りで取得

    public string Next()
    {
        if (_pos >= _line.Length)
        {
            _line = Console.ReadLine().Split(Separator);
            _pos = 0;
        }

        return _line[_pos++];
    }

    public int NextInt()
    {
        return int.Parse(Next());
    }

    public long NextLong()
    {
        return long.Parse(Next());
    }

    public double NextDouble()
    {
        return double.Parse(Next());
    }

    #endregion

    #region 型変換

    private int[] ToIntArray(string[] array)
    {
        var result = new int[array.Length];
        for (int i = 0; i < array.Length; i++)
        {
            result[i] = int.Parse(array[i]);
        }

        return result;
    }

    private long[] ToLongArray(string[] array)
    {
        var result = new long[array.Length];
        for (int i = 0; i < array.Length; i++)
        {
            result[i] = long.Parse(array[i]);
        }

        return result;
    }

    private double[] ToDoubleArray(string[] array)
    {
        var result = new double[array.Length];
        for (int i = 0; i < array.Length; i++)
        {
            result[i] = double.Parse(array[i]);
        }

        return result;
    }

    #endregion

    #region 配列取得

    public string[] Array()
    {
        if (_pos >= _line.Length)
            _line = Console.ReadLine().Split(Separator);

        _pos = _line.Length;
        return _line;
    }

    public int[] IntArray()
    {
        return ToIntArray(Array());
    }

    public long[] LongArray()
    {
        return ToLongArray(Array());
    }

    public double[] DoubleArray()
    {
        return ToDoubleArray(Array());
    }

    #endregion
}

#region PriorityQueueEX

public abstract class PQBase<T>
{
    protected Comparison<T> cmp;
    protected int Depth;
    public abstract int Count { get; }
    public abstract void Enqueue(T item);
    public abstract T Dequeue();
    public abstract T Peek();
    public abstract bool Any();
    public abstract T[] Items { get; }
}

// 通常の優先度付きキューにマージも追加
class PriorityQueueEX<T> : PQBase<T>
{
    private PriorityQueue<PQBase<T>> PQ;
    private int count;

    #region コンストラクタ

    public PriorityQueueEX() : this(Comparer<T>.Default)
    {
    }

    public PriorityQueueEX(Comparer<T> comparer) : this(comparer.Compare)
    {
    }

    public PriorityQueueEX(Comparison<T> comparison)
    {
        cmp = comparison;
        PQ = new PriorityQueue<PQBase<T>>((a, b) => comparison(a.Peek(), b.Peek()));
        PQ.Enqueue(new PriorityQueue<T>(cmp));
        Depth = 1;
    }

    #endregion

    public override int Count
    {
        get { return count; }
    }

    public override T Peek()
    {
        return PQ.Peek().Peek();
    }

    public override T Dequeue()
    {
        if (!PQ.Peek().Any())
            throw new IndexOutOfRangeException();
        var top = PQ.Dequeue();
        T result = top.Dequeue();
        if (top.Any() || !PQ.Any())
            PQ.Enqueue(top);
        count--;
        return result;
    }

    public override void Enqueue(T item)
    {
        var top = PQ.Dequeue();
        top.Enqueue(item);
        PQ.Enqueue(top);
        count++;
    }

    public override bool Any()
    {
        return Count > 0;
    }

    public override T[] Items
    {
        get
        {
            PriorityQueue<T> pq = new PriorityQueue<T>(cmp);
            foreach (PQBase<T> pqItem in PQ.Items)
            {
                foreach (T item in pqItem.Items)
                {
                    pq.Enqueue(item);
                }
            }

            return pq.Items;
        }
    }

    public static PriorityQueueEX<T> Merge(PriorityQueueEX<T> a, PriorityQueueEX<T> b)
    {
        if(!a.Any())
            if (!b.Any())
                return new PriorityQueueEX<T>(a.cmp);
            else
                return b;
        else if (!b.Any())
            return a;
        
        if (a.Depth == b.Depth)
        {
            a.Depth++;
        }

        if (a.Depth > b.Depth)
        {
            a.PQ.Enqueue(b);
            a.count += b.count;
            return a;
        }
        else
        {
            b.PQ.Enqueue(a);
            b.count += a.count;
            return b;
        }
    }

    public static PriorityQueueEX<T> operator +(PriorityQueueEX<T> a, PriorityQueueEX<T> b)
    {
        return Merge(a, b);
    }
}

/// <summary>
/// 指定した型のインスタンスを最も価値が低い順に取り出すことが可能な可変サイズのコレクションを表します．
/// </summary>
/// <typeparam name="T">優先度付きキュー内の要素の型を指定します．</typeparam>
/// <remarks>内部的にはバイナリヒープによって実装されています．</remarks>
public class PriorityQueue<T> : PQBase<T>
{
    readonly List<T> heap = new List<T>();

    /// <summary>
    /// デリゲートで表されるような比較関数を使用してインスタンスを初期化します．
    /// </summary>
    /// <param name="comparison"></param>
    /// <remarks>この操作は O(1) で実行されます．</remarks>
    public PriorityQueue(Comparison<T> comparison)
    {
        cmp = comparison;
        Depth = 1;
    }

    /// <summary>
    /// 優先度付きキューに要素を追加します．
    /// </summary>
    /// <param name="item">優先度付きキューに追加される要素</param>
    /// <remarks>最悪計算量 O(log N) で実行されます．</remarks>
    public override void Enqueue(T item)
    {
        var pos = heap.Count;
        heap.Add(item);
        while (pos > 0)
        {
            var par = (pos - 1) / 2;
            if (cmp(heap[par], item) <= 0)
                break;
            heap[pos] = heap[par];
            pos = par;
        }

        heap[pos] = item;
    }

    /// <summary>
    /// 優先度付きキューから最も価値が低い要素を削除し，返します．
    /// </summary>
    /// <returns>優先度付きキューから削除された要素．</returns>
    /// <remarks>最悪計算量 O(log N) で実行されます．</remarks>
    public override T Dequeue()
    {
        var ret = heap[0];
        var pos = 0;
        var x = heap[heap.Count - 1];

        while (pos * 2 + 1 < heap.Count - 1)
        {
            var lch = pos * 2 + 1;
            var rch = pos * 2 + 2;
            if (rch < heap.Count - 1 && cmp(heap[rch], heap[lch]) < 0) lch = rch;
            if (cmp(heap[lch], x) >= 0)
                break;
            heap[pos] = heap[lch];
            pos = lch;
        }

        heap[pos] = x;
        heap.RemoveAt(heap.Count - 1);
        return ret;
    }

    /// <summary>
    ///  優先度付きキューに含まれる最も価値が低い要素を削除せずに返します．
    /// </summary>
    /// <returns>優先度付きキューに含まれる最も価値が低い要素．</returns>
    /// <remarks>この操作は O(1) で実行されます．</remarks>
    public override T Peek()
    {
        return heap[0];
    }

    /// <summary>
    /// 優先度付きキュー内の要素の数を取得します．
    /// </summary>
    /// <returns>優先度付キュー内にある要素の数</returns>
    /// <remarks>最悪計算量 O(1) で実行されます．</remarks>
    public override int Count
    {
        get { return heap.Count; }
    }

    /// <summary>
    /// 優先度付きキュー内に要素が存在するかどうかを O(1) で判定します．
    /// </summary>
    /// <returns>優先度付キュー内にある要素が存在するならば true，そうでなければ　false．</returns>
    /// <remarks>この操作は O(1) で実行されます．</remarks>
    public override bool Any()
    {
        return heap.Count > 0;
    }

    /// <summary>
    /// 優先度付きキューに含まれる要素を昇順に並べて返します．
    /// </summary>
    /// <remarks>この操作は計算量 O(N log N)で実行されます．</remarks>
    public override T[] Items
    {
        get
        {
            var ret = heap.ToArray();
            Array.Sort(ret, cmp);
            return ret;
        }
    }
}

#endregion

class UnionFind
{
    private int[] Par, Rank;

    public UnionFind(int max)
    {
        Par = new int[max];
        Rank = new int[max];
        for (int i = 0; i < max; i++)
        {
            Par[i] = i;
        }
    }

    public int Find(int n)
    {
        if (Par[n] == n)
        {
            return n;
        }
        else
        {
            return Find(Par[n]);
        }
    }

    public bool Same(int a, int b)
    {
        return Find(a) == Find(b);
    }

    public void Union(int a, int b)
    {
        a = Find(a);
        b = Find(b);
        if (a == b) return;
        if (Rank[a] < Rank[b])
        {
            Par[a] = b;
        }
        else
        {
            Par[b] = a;
            if (Rank[a] == Rank[b]) Rank[a]++;
        }
    }
}