Pagini recente » Cod sursa (job #328055) | Profil Gainusa | Cod sursa (job #1575409) | Cod sursa (job #3121451) | Cod sursa (job #2361192)
/**APM-Kruskal**/
#include<bits/stdc++.h>
using namespace std;
struct tip
{
int cost,x,y;
};
bool cmp(tip a,tip b)
{
return a.cost<b.cost;
}
const int maxN=(2e5)+5;
vector<tip> graphEdges;
int t[maxN];
inline int getRoot(int x)
{
int y=x;
while(t[y]>0) y=t[y];
int z=x;
while(z!=y)
{
int aux=t[z];
t[z]=y;
z=aux;
}
return y;
}
inline void unite(int x,int y)
{
if(t[x]<t[y])
{
t[x]+=t[y];
t[y]=x;
}
else
{
t[y]+=t[x];
t[x]=y;
}
}
int n,m,x,y,z,sol;
vector<pair<int,int> > edges;
int main()
{
freopen("apm.in","r",stdin);
freopen("apm.out","w",stdout);
scanf("%d%d",&n,&m);
for(int i=1;i<=m;i++)
{
scanf("%d%d%d",&x,&y,&z);
graphEdges.push_back({z,x,y});
}
for(int i=1;i<=n;i++)
t[i]=-1;
sort(graphEdges.begin(),graphEdges.end(),cmp);
int cnt=0;
for(auto it:graphEdges)
{
if(cnt==(n-1)) break;
int cost,x,y;
cost=it.cost;
x=it.x;
y=it.y;
int xa,ya;
xa=getRoot(x);
ya=getRoot(y);
if(xa!=ya)
{
unite(xa,ya);
sol+=cost;
cnt++;
edges.push_back(make_pair(x,y));
}
}
printf("%d\n",sol);
printf("%d\n",n-1);
for(auto it:edges)
printf("%d %d\n",it.first,it.second);
return 0;
}