Cod sursa(job #832219)

Utilizator mihaibogdan10Mihai Bogdan mihaibogdan10 Data 10 decembrie 2012 04:36:36
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.22 kb
#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";
}