// KRUSKAL
//EFICIENT
#include <fstream>
#include <algorithm>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
struct muchie
{
int x,y,c;//c=cost
};
muchie V[400001],S[400001];//V=vectorul muchiilor, S=muchiile alese
int T[200001];//vector de "tati"
bool CMP(muchie a, muchie b)
{
return a.c<b.c;
}
int radacina(int x)
{
if(T[x]==x) return x;
else return T[x]=radacina(T[x]);
}
int main()
{
int n,m,sum=0,k=0;
fin>>n>>m;
for(int i=1;i<=m;i++)
fin>>V[i].x>>V[i].y>>V[i].c;
for(int i=1;i<=n;i++) T[i]=i;
sort(V+1, V+m+1, CMP);//ordonare muchii crescator dupa cost
for(int i=1;i<=m;i++)
{
if(radacina(V[i].x)!=radacina(V[i].y) ) //muchia nu formeaza ciclu
{ //pt ca nodurile sunt in subarbori diferiti
T[radacina(V[i].y)]=radacina(V[i].x);//unesc cei 2 subarbori
S[++k]=V[i];//retin muchia
sum+=V[i].c;//maresc suma costurilor
}
}
fout<<sum<<'\n'<<n-1<<'\n';
for(int i=1;i<=k;i++)
fout<<S[i].x<<' '<<S[i].y<<'\n';
fin.close();
fout.close();
return 0;
}
//INEFICIENT
#include<fstream>
using namespace std;
ifstream fin("k.in");
ofstream fout("k.out");
struct muchie
{
int x,y,c;
};
muchie V[100];
int n,m,A[100][100],P[100],k;
void citire()
{
fin>>n>>m;
for(int i=1;i<=m;i++)
fin>>V[i].x>>V[i].y>>V[i].c;
}
void colorare(int r,int cul)
{
int s,d,i,X[100];
s=d=1;
X[1]=r;
P[r]=1;
while(s<=d)
{
for(int i=1;i<=n;i++)
if(P[i]!=cul && A[X[s]][i])
{d++; X[d]=i; P[i]=cul;
}
s++;
}
}
void ordonare()
{
muchie aux;
for(int i=1;i<m;i++)
for(int j=i+1;j<=m;j++)
if(V[i].c>V[j].c)
{
aux=V[i];
V[i]=V[j];
V[j]=aux;
}
}
int main()
{
int i;
citire();
for(i=1;i<=n;i++) P[i]=i;
ordonare();
k=0; i=1;
while(k<n-1)
{
if(P[V[i].x]!=P[V[i].y])
{
fout<<V[i].x<<" "<<V[i].y<<" "<<V[i].c<<"\n";
A[V[i].x][V[i].y]=A[V[i].y][V[i].x]=1;
if(P[V[i].x]<P[V[i].y]) colorare(V[i].y,P[V[i].x]);
else colorare(V[i].x,P[V[i].y]);
k++;
}
i++;
}
}
//sau cu eliminare de muchii a.i. sa ramana conex
#include<fstream>
using namespace std;
ifstream fin("k.in");
ofstream fout("k.out");
struct muchie
{
int x,y,c;
};
muchie V[100];
int n,m,A[100][100],P[100],k;
void citire()
{
fin>>n>>m;
for(int i=1;i<=m;i++)
{ fin>>V[i].x>>V[i].y>>V[i].c;
A[V[i].x][V[i].y]=A[V[i].y][V[i].x]=1;
}
}
int conex()
{
int s,d,i,X[100];
s=d=1; X[1]=1; P[1]=1;
while(s<=d)
{
for(int i=1;i<=n;i++)
if(!P[i] && A[X[s]][i])
{d++; X[d]=i; P[i]=1;
}
s++;
}
if(d==n) return 1;
else return 0;
}
void ordonare()
{
muchie aux;
for(int i=1;i<m;i++)
for(int j=i+1;j<=m;j++)
if(V[i].c<V[j].c)
{
aux=V[i];
V[i]=V[j];
V[j]=aux;
}
}
int main()
{
int i;
citire();
ordonare();
k=m; i=1;
while(k>n-1)
{
A[V[i].x][V[i].y]=A[V[i].y][V[i].x]=0;
for(int j=1;j<=n;j++) P[j]=0;
if(conex()) k--;
else A[V[i].x][V[i].y]=A[V[i].y][V[i].x]=1;
i++;
}
for(int i=1;i<=n;i++)
for(int j=i+1;j<=n;j++)
if(A[i][j]) fout<<i<<" "<<j<<endl;
}
|