Pagini recente » Cod sursa (job #409304) | Cod sursa (job #958395) | Cod sursa (job #2846497) | Cod sursa (job #2768978) | Cod sursa (job #2333624)
// APM Kruskal's Algorithm
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
static const int NMAX = 400100;
int n, m;
int x[NMAX], y[NMAX], weight[NMAX], ind[NMAX];
int TT[NMAX], RG[NMAX];
vector<int> sol;
bool cmp(int a,int b)
{
return weight[a] < weight[b];
}
int find(int x)
{
int R, y;
for(R = x; TT[R] != R; R = TT[R]);
while(TT[x] != x)
{
y = TT[x];
TT[x] = R;
x = y;
}
return R;
}
void unite(int xx, int yy)
{
int x = find(xx);
int y = find(yy);
if(x == y)
return;
if(RG[x] > RG[y])
TT[y] = x;
else
TT[x] = y;
if(RG[x] == RG[y])
RG[y]++;
}
int main()
{
int total = 0;
fin >> n >> m;
for(int i = 1; i<=m ; ++i)
{
fin >> x[i] >> y[i] >> weight[i];
ind[i] = i;
}
for(int i =1 ;i <= n; ++i)
{
TT[i] = i;
RG[i] = 0;
}
sort(ind+1, ind+m+1, cmp);
for(int i = 1; i<= m; ++i)
{
int parent1 = find(x[ind[i]]);
int parent2 = find(y[ind[i]]);
if(parent1 != parent2)
{
unite(x[ind[i]],y[ind[i]]);
total+= weight[ind[i]];
sol.push_back(ind[i]);
}
}
fout << total << endl << sol.size() << endl;
for(auto it : sol)
fout << y[it] << " " << x[it] << endl;
return 0;
}