#include #include #include #include #include #define edge pair using namespace std; vector< pair > Graph, MST; int nodes, edges, parent[10001]; int findSet(int x, int *parent) { if (x != parent[x]) parent[x] = findSet(parent[x], parent); return parent[x]; } int main() { ifstream fin("input.txt"); assert( fin ); fin >> nodes >> edges; // controllo input if (!( nodes >= 1 && nodes <= 10000 && edges >= 2 && edges <= 1000000 )) return 1; // inizializzo for (int i = 1; i <= nodes; i++) parent[i] = i; MST.clear(); Graph.clear(); // popolo il grafo int u, v, w; for (int i = 0; i < edges; i++) { fin >> u >> v >> w; Graph.push_back( pair(w, edge(u,v)) ); } // eseguo Kruskal sort( Graph.begin(), Graph.end() ); int totalWeight = 0; for (int i = 0; i < edges; i++) { int pu = findSet(Graph[i].second.first, parent); int pv = findSet(Graph[i].second.second, parent); if (pu != pv) { totalWeight += Graph[i].first; MST.push_back(Graph[i]); parent[pu] = parent[pv]; } } ofstream fout("output.txt"); assert( fout ); fout << totalWeight << endl; for (int i = 0; i < MST.size(); i++) fout << MST[i].second.first << " " << MST[i].second.second << endl; fout.close(); return 0; }