Pagini recente » Cod sursa (job #324632) | Cod sursa (job #2044738) | Cod sursa (job #1593845) | Cod sursa (job #3123091) | Cod sursa (job #3253931)
#include <iostream>
#include <fstream>
#include <algorithm>
#define N 105
using namespace std;
ifstream fin ("apm.in");
ofstream fout ("apm.out");
int n,m;
int a[N][N];
int *l[N];
int lg[N];
bool vizit[N];
int que[N];
int prim,ultim;
int height[N];
int parinte[1005];
bool viz[101];
struct Muchie
{
int i,j;
int cost;
}muchie[1005];
int nrSelec=0;
int costTotal=0;
Muchie apcm[105];
void readGraph()
{
fin>>n>>m;
for(int i=1;i<=m;++i)
{
fin>>muchie[i].i>>muchie[i].j>>muchie[i].cost;
}
}
int Find(int v)
{
if(parinte[v]==0)
return v;
else
{
parinte[v]=Find(parinte[v]);
return parinte[v];
}
}
void Union(int u, int v)
{
int reprez_u=Find(u);
int reprez_v=Find(v);
if(height[reprez_u]>height[reprez_v])
{
parinte[reprez_v]=reprez_u;
}
else
{
parinte[reprez_u]=reprez_v;
if(height[reprez_u]==height[reprez_v])
height[reprez_v]=height[reprez_v]+1;
}
}
bool comp(Muchie a, Muchie b)
{
if (a.cost < b.cost)
return 1;
else
return 0;
}
void Krukal()
{
for(int i=1;i<=n;++i)
{
parinte[i]=0;
height[i]=0;
}
sort(muchie+1, muchie+m+1, comp);
for(int i=1;i<=m;++i)
{
if(Find(muchie[i].i)!=Find(muchie[i].j))
{
nrSelec++;
costTotal+=muchie[i].cost;
apcm[nrSelec]=muchie[i];
Union(muchie[i].i,muchie[i].j);
if(nrSelec==n-1)
break;
}
}
}
void kruskal2()
{
///faci union(daca nu sunt ciclu) deja la ele si apoi kruskal normal
}
void Primm()
{
}
int main()
{
readGraph();
Krukal();
fout<<nrSelec<<"\n";
fout<<costTotal<<"\n";
for(int i=1;i<=nrSelec;++i)
{
fout<<apcm[i].i<<" "<<apcm[i].j<<"\n";
}
return 0;
}