Skip to content

Instantly share code, notes, and snippets.

@rosalogia
Created October 29, 2020 04:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rosalogia/0b6f265f226d841ff83fcef096df2472 to your computer and use it in GitHub Desktop.
Save rosalogia/0b6f265f226d841ff83fcef096df2472 to your computer and use it in GitHub Desktop.
A solution to a graph theory CF practice problem in C++
#include <bits/stdc++.h>
#define N 1000010
using namespace std;
typedef long long int ll;
vector<ll> graph[N];
set<ll> seen;
ll min_cost = LLONG_MAX;
void dfs(ll costs[], ll r) {
seen.insert(r);
if (costs[r] < min_cost) min_cost = costs[r];
for (ll i : graph[r]) if (!seen.count(i)) dfs(costs, i);
}
int main() {
ll n, m, u, v;
cin >> n >> m;
ll c[n + 1];
for (int i = 1; i < n + 1; i++) cin >> c[i];
for (int i = 0; i < m; i++) {
cin >> u >> v;
graph[u].push_back(v);
graph[v].push_back(u);
}
ll cost = 0;
for (int i = 1; i <= n; i++) {
if (!seen.count(i)) {
min_cost = c[i];
dfs(c, i);
cost += min_cost;
}
}
cout << cost << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment