Number of blocks

4.3

11 votes
Graphs, Minimum Spanning Tree, Algorithms, GCD
Problem

You are given N cities and the ith city contains a[i] blocks. If you want to build a road between ith and jth cities (ij), then the number of blocks needed is gcd(a[i],a[j]). Here gcd is the greatest common divisor. You have to build roads in such a way that any person can go from any city to another city in exactly one way, not more than one way between two cities. You have to maximize the total number of blocks used to build roads.

Input format

  • The first line contains N denoting the number of cities.
  • The second line contains N integers, a[1],a[2],...,a[N] where a[i] is the number of blocks in the ith city.  

Output format

Print a maximum number of blocks used to build roads in such a way the provided condition is satisfied.

Constraints

1N1000001a[i]100000

 

 

 

Time Limit: 2
Memory Limit: 256
Source Limit:
Explanation

Here the optimal solution is to build one road between 1st and 2nd cities and the second road is between 2nd and 3rd cities. 
Total number of blocks used to built roads = gcd(4, 6) + gcd(6, 9) = 2 + 3 = 5. 

In this structure, We can go from any city to another city in exactly one way so the given condition is also satisfied.

Editor Image

?