Pagini recente » Cod sursa (job #2642446) | ioit | Cod sursa (job #2137108) | Cod sursa (job #1169110) | Cod sursa (job #2333637)
// 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)
{
if(TT[x] != x)
TT[x] = find(TT[x]);
return TT[x];
}
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]++;
*/
TT[find(xx)] = find(yy);
}
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)
{
if(find(x[ind[i]]) != find(y[ind[i]]))
{
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;
}