Untitled
unknown
plain_text
2 years ago
1.5 kB
1
Indexable
Never
#include <iostream> #include <algorithm> #include <vector> using namespace std; struct Edge { int u, v, cost; }; bool cmp(const Edge& a, const Edge& b) { return a.cost < b.cost; } int find(vector<int>& parent, int i) { if (parent[i] == i) return i; return parent[i] = find(parent, parent[i]); } void merge(vector<int>& parent, vector<int>& rank, int x, int y) { int px = find(parent, x), py = find(parent, y); if (rank[px] > rank[py]) parent[py] = px; else if (rank[px] < rank[py]) parent[px] = py; else { parent[py] = px; rank[px]++; } } int main() { int n, m; cin >> n >> m; vector<Edge> edges(m); for (int i = 0; i < m; i++) { cin >> edges[i].u >> edges[i].v >> edges[i].cost; } sort(edges.begin(), edges.end(), cmp); vector<int> parent(n); vector<int> rank(n, 0); for (int i = 0; i < n; i++) { parent[i] = i; } vector<Edge> mst; int cost = 0; for (int i = 0; i < m; i++) { Edge e = edges[i]; if (find(parent, e.u) != find(parent, e.v)) { cost += e.cost; mst.push_back(e); merge(parent, rank, e.u, e.v); } } cout << "Costul minim al arborelui de acoperire este: " << cost << endl; cout << "Muchiile arborelui de acoperire sunt: " << endl; for (int i = 0; i < mst.size(); i++) { cout << mst[i].u << " - " << mst[i].v <<" si costul "<< mst[i].cost << endl; } return 0; }