Pagini recente » Cod sursa (job #2646982) | Cod sursa (job #3002323) | Cod sursa (job #3278609) | Cod sursa (job #2728859) | Cod sursa (job #3278105)
#include <iostream>
#include <fstream>
#include <queue>
#include <bitset>
#include <vector>
#include <array>
#include <stack>
#include <algorithm>
#define maxSize 100001
using namespace std;
vector<array<int, 3>> readEdgeListWeighted(ifstream &fin, int nodes, int edges) {
vector<array<int, 3>> edgeList;
for (int i = 0; i < edges; i++) {
int x, y, weight;
fin >> x >> y >> weight;
edgeList.push_back({x, y, weight});
}
return edgeList;
}
struct dsu {
vector<int> root;
vector<int> height;
dsu(int n) {
height.resize(n+1, 0);
root.resize(n+1);
for (int i = 1; i <= n; i++) {
root[i] = i;
}
}
int findRoot(int node) {
if (node != root[node]) {
root[node] = findRoot(root[node]);
}
return root[node];
}
void unionNodes(int u, int v) {
int rootU = findRoot(u);
int rootV = findRoot(v);
if(rootU == rootV) {
return;
}
if(height[rootU] < height[rootV]) {
root[rootU] = rootV;
}
else if(height[rootU] > height[rootV]) {
root[rootV] = rootU;
}
else {
root[rootU] = rootV;
height[rootV]++;
}
}
bool areConnected(int u, int v) {
return findRoot(u) == findRoot(v);
}
};
vector<array<int, 3>> kruskal(int& finalCost,const int& nodes, vector<array<int, 3>> &edgeList) {
sort(edgeList.begin(), edgeList.end(), [](const array<int, 3>& a, const array<int, 3>& b) {
return a[2] < b[2];
});
dsu dsu(nodes);
vector<array<int, 3>> mst;
for (const auto& edge : edgeList) {
int u = edge[0];
int v = edge[1];
int weight = edge[2];
if (!dsu.areConnected(u, v)) {
finalCost += weight;
mst.push_back(edge);
dsu.unionNodes(u, v);
}
if (mst.size() == nodes - 1) {
break;
}
}
return mst;
}
int main() {
ifstream fin("apm.in");
ofstream fout("apm.out");
int finalCost = 0;
int nodes, edges;
fin >> nodes >> edges;
auto edgeList = readEdgeListWeighted(fin, nodes, edges);
auto mst = kruskal(finalCost, nodes, edgeList);
fout << finalCost << endl;
fout << mst.size() << endl;
for (auto elem : mst) {
fout << elem[1] << " " << elem[0] << endl;
}
fin.close();
fout.close();
return 0;
}