Pagini recente » Cod sursa (job #60189) | Cod sursa (job #3252661) | Cod sursa (job #2999439) | Cod sursa (job #87257) | Cod sursa (job #2187203)
#include <fstream>
#include<set>
#include<vector>
using namespace std;
ifstream f("apm.in");
ofstream g("apm.out");
int n,m,r[200002],p[200002],cost;
struct muchie{int x; int y; int c; friend bool operator <(muchie m1, muchie m2){return(m1.c<m2.c ||(m1.c==m2.c && m1.x<m2.x) || (m1.c==m2.c && m1.x==m2.x && m1.y<m2.y));}};
set<muchie>v;
vector<pair<int, int> >APM;
void make_set()
{
for(int i=1;i<=n;i++)
{
p[i]=i; r[i]=1;
}
}
int Find(int x)
{
if(p[x]!=x) p[x]=Find(p[x]);
return p[x];
}
void Union(int x, int y)
{
int xroot,yroot;
xroot=Find(x); yroot=Find(y);
if(r[xroot]<r[yroot])
{
r[yroot]+=r[xroot];
p[xroot]=yroot;
}
else
{
r[xroot]+=r[yroot];
p[yroot]=xroot;
}
}
int main()
{
int i;
muchie aux;
int x,y,c;
f>>n>>m;
for(i=1;i<=m;i++)
{
f>>x>>y>>c;
aux.x=x; aux.y=y; aux.c=c;
v.insert(aux);
}
make_set();
set<muchie>::iterator it;
for(it=v.begin();it!=v.end();++it)
{
x=it->x; y=it->y; c=it->c;
if(Find(x)!=Find(y))
{
Union(x,y);
cost+=c;
APM.push_back(make_pair(x,y));
}
}
g<<cost<<'\n';
g<<APM.size()<<'\n';
vector<pair<int,int> >::iterator it1;
for(it1=APM.begin();it1!=APM.end();it1++)
g<<it1->first<<' '<<it1->second<<'\n';
f.close();
g.close();
return 0;
}