Pagini recente » Cod sursa (job #1594691) | Cod sursa (job #1341287) | Cod sursa (job #2000777) | Cod sursa (job #2443109) | Cod sursa (job #2556494)
#include <fstream>
#include <algorithm>
using namespace std;
ifstream f("apm.in");
ofstream g("apm.out");
struct muchii
{
int x, y, cost;
bool operator <(muchii other)
{
return cost < other.cost;
}
};
int tati[200005], n, m, sum;
muchii graf[400005], rez[200005];
int addedEdges = 0;
int getRoot(int x)
{
if(tati[x] == 0)
return x;
tati[x] = getRoot(tati[x]);
return tati[x];
}
void read()
{
f>>n>>m;
for(int i = 0; i<m; ++i)
{
f>>graf[i].x>>graf[i].y>>graf[i].cost;
}
sort(graf, graf+m);
}
void solve()
{
int xRoot, yRoot;
for(int k = 0; addedEdges < n-1 && k < m; ++k)
{
xRoot = getRoot(graf[k].x);
yRoot = getRoot(graf[k].y);
if(xRoot != yRoot)
{
tati[xRoot] = yRoot;
sum += graf[k].cost;
rez[addedEdges++] = graf[k];
}
}
}
void print()
{
g<<sum<<"\n";
g<<addedEdges<<"\n";
for(int i = 0; i<addedEdges; ++i)
{
g<<rez[i].x<<" "<<rez[i].y<<"\n";
}
}
int main()
{
read();
solve();
print();
return 0;
}