Pagini recente » Cod sursa (job #1993454) | Cod sursa (job #1115356) | Cod sursa (job #2839013) | Cod sursa (job #1434675) | Cod sursa (job #3255793)
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#define Nmax 200000
//#define Mmax 400000
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
vector<pair<pair<int,int>,int>> g;
vector<pair<int,int>> sol;
int rang[Nmax + 5] ,TT[Nmax + 5];
int n,m,sum,x,y,c;
int Find(int Node)
{
if(TT[Node] == Node)
return Node;
else
return Find(TT[Node]);
}
void Unite(int x , int y)
{
if(rang[x]<rang[y])
swap(x,y);
if(rang[x] == rang[y])
rang[x]++;
TT[y] = x;
}
void kruskal (vector<pair<pair<int,int>,int>> g , vector<pair<int,int>> solution , int &sum)
{
for(auto i : g)
{
int a = Find(i.first.first);
int b = Find(i.first.second);
if(a!=b)
{
sum+=i.second;
Unite(a,b);
solution.push_back(make_pair(i.first.first,i.first.second));
}
}
}
int main()
{
fin>>n>>m;
for(int i=1;i<=m;i++)
{
fin>>x>>y>>c;
g.push_back(make_pair(make_pair(x,y),c));
}
for(int i=1;i<=n;i++)
{
TT[i]=i;
}
sort(g.begin(),g.end(),[](auto &left,auto &right)
{
return left.second < right.second;
});
/*for(auto i : g)
{
int a = Find(i.first.first);
int b = Find(i.first.second);
if(a != b)
{
sum += i.second;
Unite(a,b);
sol.push_back(make_pair(i.first.first,i.first.second));
}
}*/
kruskal(g,sol,sum);
fout << sum << '\n';
fout << sol.size() << '\n';
for(auto i : sol)
{
fout << i.first << " " << i.second << '\n';
}
return 0;
}