Pagini recente » Borderou de evaluare (job #2960960) | Borderou de evaluare (job #626406) | Borderou de evaluare (job #441369) | Borderou de evaluare (job #715843) | Cod sursa (job #2124903)
#include <bits/stdc++.h>
using namespace std;
constexpr int NMax=200005;
constexpr int MMax=400005;
ifstream fin("apm.in");
ofstream fout("apm.out");
int N,M;
struct Edge
{
int x,y,z;
} edge[MMax];
int father[NMax],state[NMax];
int totalCost;
vector< pair<int,int> > sol;
bool cmp(Edge a, Edge b){ return a.z<b.z; }
int GetRoot(int root)
{
for(;root!=father[root];root=father[root]);
return root;
}
void Unite(int x,int y)
{
if(state[x]>state[y])
father[y]=x;
else
father[x]=y;
if(state[x]==state[y])
state[y]++;
}
void Kruskal()
{
sort(edge+1,edge+1+M,cmp);
for(int i=1;i<=N;i++)
father[i]=state[i]=i;
for(int i=1;i<=M;i++)
{
int x=edge[i].x;
int y=edge[i].y;
int rootx=GetRoot(x);
int rooty=GetRoot(y);
if(rootx!=rooty)
{
Unite(rootx,rooty);
sol.push_back({x,y});
totalCost+=edge[i].z;
}
}
}
int main()
{
fin>>N>>M;
for(int i=1;i<=M;i++)
fin>>edge[i].x>>edge[i].y>>edge[i].z;
Kruskal();
fout<<totalCost<<"\n";
fout<<sol.size()<<"\n";
for(auto child : sol)
fout<<child.first<<" "<<child.second<<"\n";
return 0;
}