Pagini recente » Cod sursa (job #273420) | Cod sursa (job #2105161) | Cod sursa (job #441588) | Cod sursa (job #1004966) | Cod sursa (job #3308775)
#include <iostream>
#include <algorithm>
#include <fstream>
#include <cmath>
#include <vector>
using namespace std;
ifstream f("apm.in");
ofstream g("apm.out");
struct drum{
int a, b, c;
};
bool comp( drum x, drum xx )
{
if( x.c == xx.c )
return true;
return x.c <= xx.c;
}
const int maxN = 2e5;
int parinte[ maxN+1 ], dim[ maxN+1 ], n, m, ans = 0;
vector<drum> adj;
void precal()
{
for( int i = 1; i <= maxN; ++i )
dim[i] = 1, parinte[i] = i;
}
int p( int x )
{
if( parinte[x] != x )
{
int nextParinte = p( parinte[x] );
parinte[x] = nextParinte;
return nextParinte;
}
return x;
}
bool unf( int x, int y )
{
if( p(x) == p(y) )
return false;
else
{
int rootx = p(x), rooty = p(y);
if( dim[x] >= dim[y] )
{
parinte[ rooty ] = rootx;
dim[ rootx ] += dim[ rooty ];
}
else
{
parinte[ rootx ] = rooty;
dim[ rooty ] += dim[ rootx ];
}
return true;
}
}
int main() {
ios_base::sync_with_stdio(false);
f.tie(nullptr);
g.tie(nullptr);
precal();
f >> n >> m;
for( int i = 1; i <= m; ++i )
{
int a, b, c;
f >> a >> b >> c;
drum r;
r.a = a, r.b = b, r.c = c;
adj.push_back( r );
}
sort( adj.begin(), adj.end(), comp );
vector<pair<int, int> > ansList;
for( int i = 0; i < m; ++i )
{
int g = adj[i].a, h = adj[i].b, l = adj[i].c;
bool ok = unf( g,h );
if( ok == true )
{
pair<int,int> rr;
rr.first = g;
rr.second = h;
ans += l;
ansList.push_back(rr);
}
}
g << ans << "\n" << n-1 << "\n";
for( int i = 0; i < ansList.size(); ++i )
{
g << ansList[i].first << " " << ansList[i].second << "\n";
}
return 0;
}