In this HackerEarth Number of blocks problem solution 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 (i!=j), 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.


HackerEarth Number of blocks problem solution


HackerEarth Number of blocks problem solution.

#include <bits/stdc++.h>
using namespace std;

#define ll long long
#define pb push_back
#define all(x) x.begin(),x.end()

#define pll pair<ll,ll>
#define ff first
#define ss second

#define MOD 1000000007

const int N = 100005;

vector<int> v[N];

struct DSU
{
vector<ll> p,sz;
void intialize(int x)
{
p.resize(x+5);
sz.resize(x+5);
for(ll i=0;i<x;i++) p[i] = i,sz[i] = 1;
}
ll getp(ll k)
{
while(k!=p[k])
{
p[k]=p[p[k]];
k=p[k];
}
return k;
}
ll getsize(ll k)
{
return sz[getp(k)];
}
void unionn(ll u,ll v)
{
ll p1=getp(u),p2=getp(v);
if(p1==p2) return;
if(sz[p1]>sz[p2]) swap(p1,p2);
sz[p2]+=sz[p1];
sz[p1]=0;
p[p1]=p[p2];
}
};

void solve()
{
int n;
cin >> n;
for(int i = 0, x; i < n; i++) {
cin >> x;
v[x].pb(i);
}
DSU dsu;
dsu.intialize(n + 5);

long long ans = 0;

for(int i = N - 1; i >= 1; i--) {

for(int j = 1; j < v[i].size(); j++) {
dsu.unionn(v[i][j], v[i][j - 1]);
ans += i;
}

vector<int> ids;
if(v[i].size() > 0) {
ids.pb(v[i][0]);
}
for(int j = i + i; j < N; j += i) {
if(v[j].size() > 0) {
ids.pb(v[j][0]);
}
}
for(int j = 1; j < ids.size(); j++) {
if(dsu.getp(ids[j]) != dsu.getp(ids[j - 1])) {
ans += i;
dsu.unionn(ids[j], ids[j - 1]);
}
}
}

cout << ans << "\n";
}

int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0), cout.tie(0);

int t = 1;
for(int i = 1; i < t + 1; i++) {
solve();
}

}

Second solution

#include <bits/stdc++.h>

using namespace std;
typedef long long ll;
const int N = 1e5 + 14;

struct Dsu {
int par[N];

Dsu() { memset(par, -1, sizeof par); }

int root(int v) {
return par[v] < 0 ? v : par[v] = root(par[v]);
}

bool fri(int v, int u) {
return root(v) == root(u);
}

bool merge(int v, int u) {
if ((v = root(v)) == (u = root(u)))
return 0;
par[u] += par[v];
par[v] = u;
return 1;
}
} dsu;

int t, n;
vector<int> have[N];

int main() {
ios::sync_with_stdio(0), cin.tie(0);
cin >> n;
for (int i = 0; i < n; ++i) {
int x;
cin >> x;
have[x].push_back(i);
}
ll ans = 0;
for (int w = N - 1; w >= 1; --w) {
int r = -1;
for (int i = w; i < N; i += w)
for(auto x : have[i])
if(r == -1)
r = x;
else if(dsu.merge(r, x))
ans += w;
}
cout << ans << '\n';
}