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 Rust (1.15.1) (judge verdict: Wrong Answer)

/**
 *  _           _                 __                            _   _ _   _                                 _                    _                  _
 * | |         | |               / /                           | | (_) | (_)                               | |                  (_)                | |
 * | |__   __ _| |_ ___   ___   / /__ ___  _ __ ___  _ __   ___| |_ _| |_ ___   _____ ______ _ __ _   _ ___| |_ ______ ___ _ __  _ _ __  _ __   ___| |_ ___
 * | '_ \ / _` | __/ _ \ / _ \ / / __/ _ \| '_ ` _ \| '_ \ / _ \ __| | __| \ \ / / _ \______| '__| | | / __| __|______/ __| '_ \| | '_ \| '_ \ / _ \ __/ __|
 * | | | | (_| | || (_) | (_) / / (_| (_) | | | | | | |_) |  __/ |_| | |_| |\ V /  __/      | |  | |_| \__ \ |_       \__ \ | | | | |_) | |_) |  __/ |_\__ \
 * |_| |_|\__,_|\__\___/ \___/_/ \___\___/|_| |_| |_| .__/ \___|\__|_|\__|_| \_/ \___|      |_|   \__,_|___/\__|      |___/_| |_|_| .__/| .__/ \___|\__|___/
 *                                                  | |                                                                           | |   | |
 *                                                  |_|                                                                           |_|   |_|
 *
 * https://github.com/hatoo/competitive-rust-snippets
 */
#[allow(unused_imports)]
use std::cmp::{max, min, Ordering};
#[allow(unused_imports)]
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};
#[allow(unused_imports)]
use std::iter::FromIterator;
#[allow(unused_imports)]
use std::io::{stdin, stdout, BufWriter, Write};
mod util {
    use std::io::{stdin, stdout, BufWriter, StdoutLock};
    use std::str::FromStr;
    use std::fmt::Debug;
    #[allow(dead_code)]
    pub fn line() -> String {
        let mut line: String = String::new();
        stdin().read_line(&mut line).unwrap();
        line.trim().to_string()
    }
    #[allow(dead_code)]
    pub fn gets<T: FromStr>() -> Vec<T>
    where
        <T as FromStr>::Err: Debug,
    {
        let mut line: String = String::new();
        stdin().read_line(&mut line).unwrap();
        line.split_whitespace()
            .map(|t| t.parse().unwrap())
            .collect()
    }
    #[allow(dead_code)]
    pub fn with_bufwriter<F: FnOnce(BufWriter<StdoutLock>) -> ()>(f: F) {
        let out = stdout();
        let writer = BufWriter::new(out.lock());
        f(writer)
    }
}
#[allow(unused_macros)]
macro_rules ! get { ( $ t : ty ) => { { let mut line : String = String :: new ( ) ; stdin ( ) . read_line ( & mut line ) . unwrap ( ) ; line . trim ( ) . parse ::<$ t > ( ) . unwrap ( ) } } ; ( $ ( $ t : ty ) ,* ) => { { let mut line : String = String :: new ( ) ; stdin ( ) . read_line ( & mut line ) . unwrap ( ) ; let mut iter = line . split_whitespace ( ) ; ( $ ( iter . next ( ) . unwrap ( ) . parse ::<$ t > ( ) . unwrap ( ) , ) * ) } } ; ( $ t : ty ; $ n : expr ) => { ( 0 ..$ n ) . map ( | _ | get ! ( $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ ( $ t : ty ) ,*; $ n : expr ) => { ( 0 ..$ n ) . map ( | _ | get ! ( $ ( $ t ) ,* ) ) . collect ::< Vec < _ >> ( ) } ; ( $ t : ty ;; ) => { { let mut line : String = String :: new ( ) ; stdin ( ) . read_line ( & mut line ) . unwrap ( ) ; line . split_whitespace ( ) . map ( | t | t . parse ::<$ t > ( ) . unwrap ( ) ) . collect ::< Vec < _ >> ( ) } } ; }
#[allow(unused_macros)]
macro_rules ! debug { ( $ ( $ a : expr ) ,* ) => { println ! ( concat ! ( $ ( stringify ! ( $ a ) , " = {:?}, " ) ,* ) , $ ( $ a ) ,* ) ; } }

#[allow(dead_code)]
/// Union Find Tree
pub struct UFT {
    pub par: Vec<usize>,
    pub rank: Vec<usize>,
}
impl UFT {
    #[allow(dead_code)]
    pub fn new(n: usize) -> Self {
        UFT {
            par: (0..n).collect(),
            rank: vec![0; n],
        }
    }
    #[allow(dead_code)]
    pub fn find(&mut self, x: usize) -> usize {
        if self.par[x] == x {
            x
        } else {
            let p = self.par[x];
            let pp = self.find(p);
            self.par[x] = pp;
            pp
        }
    }
    #[allow(dead_code)]
    pub fn unite(&mut self, x: usize, y: usize) {
        let x = self.find(x);
        let y = self.find(y);
        if x == y {
            return;
        }
        if self.rank[x] < self.rank[y] {
            self.par[x] = y;
        } else {
            self.par[y] = x;
            if self.rank[x] == self.rank[y] {
                self.rank[x] += 1;
            }
        }
    }
}

#[derive(Eq, PartialEq, Clone, Debug)]
/// Equivalent to std::cmp::Reverse
pub struct Rev<T>(pub T);
impl<T: PartialOrd> PartialOrd for Rev<T> {
    fn partial_cmp(&self, other: &Rev<T>) -> Option<Ordering> {
        other.0.partial_cmp(&self.0)
    }
}
impl<T: Ord> Ord for Rev<T> {
    fn cmp(&self, other: &Rev<T>) -> Ordering {
        other.0.cmp(&self.0)
    }
}

struct CmpBy<T, U>(T, U);
impl<T: PartialEq, U> PartialEq for CmpBy<T, U> {
    fn eq(&self, other: &Self) -> bool {
        (self.0).eq(&other.0)
    }
}
impl<T: Eq, U> Eq for CmpBy<T, U> {}

impl<T: PartialOrd, U> PartialOrd for CmpBy<T, U> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        (self.0).partial_cmp(&other.0)
    }
}
impl<T: Ord, U> Ord for CmpBy<T, U> {
    fn cmp(&self, other: &Self) -> Ordering {
        (self.0).cmp(&other.0)
    }
}

#[allow(dead_code)]
fn main() {
    let (n, m) = get!(usize, usize);
    let a = util::gets::<u64>();
    let es = get!(usize, usize; m);

    let mut uft = UFT::new(n);

    for &(x, y) in &es {
        uft.unite(x, y);
    }

    let mut groups = HashMap::new();

    for i in 0..n {
        groups.entry(uft.find(i)).or_insert(Vec::new()).push(a[i]);
    }

    let mut hs: BinaryHeap<CmpBy<Rev<u64>, BinaryHeap<Rev<u64>>>> = BinaryHeap::new();
    let mut singles: BinaryHeap<Rev<u64>> = BinaryHeap::new();

    for (_, g) in groups {
        if g.len() == 1 {
            singles.push(Rev(g[0]));
        } else {
            let h = g.into_iter().map(|x| Rev(x)).collect::<BinaryHeap<_>>();
            hs.push(CmpBy(h.peek().cloned().unwrap(), h));
        }
    }

    let mut ans = 0;

    while let Some(Rev(x)) = singles.pop() {
        if let Some(CmpBy(Rev(y), mut h)) = hs.pop() {
            ans += x + y;
            h.pop();
            if h.len() == 1 {
                singles.push(h.pop().unwrap());
            } else {
                hs.push(CmpBy(h.peek().cloned().unwrap(), h));
            }
        } else {
            if singles.len() == 1 {
                let Rev(y) = singles.pop().unwrap();
                ans += x + y
            } else if singles.len() > 1 {
                println!("Impossible");
                return;
            }
        }
    }

    while hs.len() > 1 {
        let CmpBy(Rev(x), mut h1) = hs.pop().unwrap();
        let CmpBy(Rev(y), mut h2) = hs.pop().unwrap();

        ans += x + y;

        let h = if h1.len() > h2.len() {
            h1.append(&mut h2);
            h1
        } else {
            h2.append(&mut h1);
            h2
        };

        hs.push(CmpBy(h.peek().cloned().unwrap(), h));
    }

    println!("{}", ans);
}