Pagini recente » Atasamentele paginii Info Oltenia 2019 Proba Individuala Clasa a 10-a | Cod sursa (job #3266013) | Cod sursa (job #2383511) | Cod sursa (job #832219)
Cod sursa(job #832219)
#include<fstream>
#include<vector>
#include<algorithm>
using namespace std;
ifstream fin("apm.in"); ofstream fout("apm.out");
struct muchie{ int x, y, c;};
vector <muchie> graf, sol;
vector <int> tata, rang;
int n, m, mAlese, cost;
bool Compara(muchie a, muchie b){
return a.c < b.c;
}
int Find(int x){
if (x == tata[x]) return x;
else {
tata[x] = Find(tata[x]);
return tata[x];
}
}
void Union(muchie &M){
int xRoot = Find(M.x), yRoot = Find(M.y);
if (xRoot == yRoot) return;
mAlese++; cost+= M.c; sol.push_back((muchie){M.x, M.y, M.c});
(rang[xRoot] >= rang[yRoot]) ? tata[yRoot] = xRoot : tata[xRoot] = yRoot;
if (rang[xRoot] == rang[yRoot]) rang[xRoot] ++;
}
int main(){
int i, x, y, c;
fin >> n >> m;
for (i = 0; i < m; i++){
fin >> x >> y >> c;
graf.push_back((muchie){x, y, c});
}
for (i = 0; i <= n; i++) tata.push_back(i);
rang.assign(n+1, 1);
sort (graf.begin(), graf.end(), Compara);
for (i = 0; i < m && mAlese < n-1; i++)
Union(graf[i]);
fout << cost << " " << sol.size() << "\n";
for (i = 0; i < n-1; i++) fout << sol[i].x << " " << sol[i].y << "\n";
}