Pagini recente » Cod sursa (job #2754926) | Cod sursa (job #2360767) | Cod sursa (job #135683) | Cod sursa (job #1625034) | Cod sursa (job #2543883)
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#define M 400005
#define N 200002
using namespace std;
pair <int,int>p[M];
int k,n,m,tot,t[N],r[N];
struct muchie
{
int st,dr,cost;
};
vector <muchie> v;
bool cmp(muchie a, muchie b)
{
return a.cost<b.cost;
}
void citire()
{
ifstream x("apm.in");
x>>n>>m;
for(int i=0;i<m;i++){
muchie p;
x>>p.st>>p.dr>>p.cost;
v.push_back(p);
}
sort(v.begin(),v.end(),cmp);
for(int i=1;i<=n;i++)
t[i]=i,r[i]=1;
x.close();
}
int tata(int nod)
{
while(t[nod]!=nod)
nod=t[nod];
return nod;
}
void uni(int noda,int nodb)
{
if(r[noda]<r[nodb])
t[noda]=nodb;
if(r[noda]>r[nodb])
t[nodb]=noda;
if(r[noda]==r[nodb])
t[noda]=nodb,r[nodb]++;
}
void solve()
{
int t1,t2;
for(int i=0;i<m;i++)
{
t1=tata(v[i].st); t2=tata(v[i].dr);
if(t1!=t2)
{
uni(t1,t2);
p[++k].first=v[i].st;
p[k].second=v[i].dr;
tot+=v[i].cost;
}
}
}
void afis()
{
ofstream y("apm.out");
y<<tot<<"\n";
y<<n-1<<"\n";
for(int i=1;i<n;i++)
y<<p[i].first<<" "<<p[i].second<<"\n";
y.close();
}
int main()
{
citire();
solve();
afis();
}