The Child and Zoo (Codeforces 438B)
Tags: DP, dsu

Of course our child likes walking in a zoo. The zoo has n areas, that are numbered from 1 to n. The i-th area contains ai animals in it. Also there are m roads in the zoo, and each road connects two distinct areas. Naturally the zoo is connected, so you can reach any area of the zoo from any other area using the roads.Our child is very smart. Imagine the child want to go from area p to area q. Firstly he considers all the simple routes from p to q. For each route the child writes down the number, that is equal to the minimum number of animals among the route areas. Let's denote the largest of the written numbers as f(p, q). Finally, the child chooses one of the routes for which he writes down the value f(p, q).After the child has visited the zoo, he thinks about the question: what is the average value of f(p, q) for all pairs p, q (p ≠ q)? Can you answer his question?

Input: The first line contains two integers n and m (2 ≤ n ≤ 105; 0 ≤ m ≤ 105). The second line contains n integers: a1, a2, ..., an (0 ≤ ai ≤ 105). Then follow m lines, each line contains two integers xi and yi (1 ≤ xi, yi ≤ n; xi ≠ yi), denoting the road between areas xi and yi.All roads are bidirectional, each pair of areas is connected by at most one road.

Output: Output a real number — the value of .The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 4.

Note: Consider the first sample. There are 12 possible situations:  p = 1, q = 3, f(p, q) = 10.  p = 2, q = 3, f(p, q) = 20.  p = 4, q = 3, f(p, q) = 30.  p = 1, q = 2, f(p, q) = 10.  p = 2, q = 4, f(p, q) = 20.  p = 4, q = 1, f(p, q) = 10. Another 6 cases are symmetrical to the above. The average is .Consider the second sample. There are 6 possible situations:  p = 1, q = 2, f(p, q) = 10.  p = 2, q = 3, f(p, q) = 20.  p = 1, q = 3, f(p, q) = 10. Another 3 cases are symmetrical to the above. The average is .

Sample Inputs:
4 3
10 20 30 40
1 3
2 3
4 3

3 3
10 20 30
1 2
2 3
3 1

7 8
40 20 10 30 20 50 40
1 2
2 3
3 4
4 5
5 6
6 7
1 4
5 7

Sample Outputs:
16.666667

13.333333

18.571429

Solution (Python):
(n, m) = map(int, input().split())
(p, c) = (list(range(n + 1)), [1] * (n + 1))
v = [0] + list(map(int, input().split()))
(s, e) = (0, [()] * m)
for i in range(m):
    (x, y) = map(int, input().split())
    e[i] = (x, y, min(v[x], v[y]))
e.sort(key=lambda x: x[2], reverse=True)
q = [[i] for i in range(n + 1)]
for (l, r, v) in e:
    (l, r) = (p[l], p[r])
    if l == r:
        continue
    if len(q[l]) > len(q[r]):
        (l, r) = (r, l)
    q[r].extend(q[l])
    for t in q[l]:
        p[t] = r
    s += c[l] * c[r] * v
    c[r] += c[l]
print(s * 2 / (n * (n - 1)))

Solution (Python):
R = lambda : map(int, input().split())
(n, m) = R()
a = list(R())
(p, f, sz) = ([], [], [])
e = [[] for i in range(n)]
vis = [0] * n
ans = 0

def find(u):
    if f[u] != u:
        f[u] = find(f[u])
    return f[u]
for i in range(n):
    p.append([a[i], i])
    f.append(i)
    sz.append(1)
p.sort()
p.reverse()
for i in range(m):
    (u, v) = R()
    e[u - 1].append(v - 1)
    e[v - 1].append(u - 1)
for i in range(n):
    u = p[i][1]
    for v in e[u]:
        if vis[v] and find(u) != find(v):
            (pu, pv) = (u, v)
            if sz[f[u]] > sz[f[v]]:
                (pu, pv) = (pv, pu)
            ans += p[i][0] * sz[f[pu]] * sz[f[pv]]
            sz[f[pv]] += sz[f[pu]]
            f[f[pu]] = f[pv]
    vis[u] = 1
print('%.6f' % (2.0 * ans / n / (n - 1)))

Solution (Python):
from io import BytesIO, IOBase
import sys
import os
import bisect
import math
import random
from collections import Counter, defaultdict, deque
from functools import cmp_to_key, lru_cache, reduce
from heapq import heapify, heappop, heappush, heappushpop, nlargest, nsmallest
from itertools import accumulate, combinations, permutations
from operator import add, iand, ior, itemgetter, mul, xor
from string import ascii_lowercase, ascii_uppercase
from typing import *

class IOWrapper(IOBase):

    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode('ascii'))
        self.read = lambda : self.buffer.read().decode('ascii')
        self.readline = lambda : self.buffer.readline().decode('ascii')
BUFSIZE = 4096

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = 'x' in file.mode or 'r' not in file.mode
        self.write = self.buffer.write if self.writable else None

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b'\n') + (not b)
            ptr = self.buffer.tell()
            (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            (self.buffer.truncate(0), self.buffer.seek(0))

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
        self.newlines = 0
        return self.buffer.read()
sys.stdin = IOWrapper(sys.stdin)
sys.stdout = IOWrapper(sys.stdout)
input = lambda : sys.stdin.readline().rstrip('\r\n')

def I():
    return input()

def II():
    return int(input())

def MII():
    return map(int, input().split())

def LI():
    return list(input().split())

def LII():
    return list(map(int, input().split()))

def GMI():
    return map(lambda x: int(x) - 1, input().split())

def LGMI():
    return list(map(lambda x: int(x) - 1, input().split()))
inf = float('inf')

class UnionFind:

    def __init__(self, n):
        self.parent = list(range(n))
        self.size = [1] * n

    def find(self, a):
        a = self.parent[a]
        acopy = a
        while a != self.parent[a]:
            a = self.parent[a]
        while acopy != a:
            (self.parent[acopy], acopy) = (a, self.parent[acopy])
        return a

    def merge(self, a, b):
        if self.find(b) != self.find(a):
            self.size[self.find(a)] += self.size[self.find(b)]
            self.parent[self.find(b)] = self.find(a)

    def getSize(self, a):
        return self.size[self.find(a)]
(n, m) = MII()
nums = LII()
path = [[] for _ in range(n)]
for _ in range(m):
    (u, v) = GMI()
    path[u].append(v)
    path[v].append(u)
union = UnionFind(n)
vis = [0] * n
res = 0
for i in sorted(range(n), key=lambda x: -nums[x]):
    tot_size = union.getSize(i)
    tmp = -tot_size * (tot_size - 1)
    vis[i] = 1
    for j in path[i]:
        if vis[j] and union.find(j) != union.find(i):
            new_size = union.getSize(j)
            tmp -= new_size * (new_size - 1)
            tot_size += new_size
            union.merge(i, j)
    tmp += tot_size * (tot_size - 1)
    res += tmp * nums[i]
print(res / n / (n - 1))