#include<fstream>
using namespace std;
ifstream fin("k.in");
ofstream fout("k.out");
const int inf=1<<20;
int n,m,A[100][100],P[100];
void citire()
{ int i,j,k,c;
fin>>n>>m;
for(i=1;i<n;i++)
for(j=i+1;j<=n;j++)
A[i][j]=A[j][i]=inf;
for(int k=1;k<=m;k++)
{ fin>>i>>j>>c;
A[i][j]=A[j][i]=c;
}
}
int main()
{
int i,j,k,minn,x,y;
citire();
P[1]=1;
for(k=1;k<n;k++)
{
minn=inf;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(P[i] && !P[j] && A[i][j]<minn)
{
minn=A[i][j]; x=i;y=j;
}
fout<<x<<" "<<y<<" "<<A[x][y]<<endl;
P[y]=1;
}
fin.close();
fout.close();
return 0;
}
//varianta eficienta
#include<fstream>
using namespace std;
ifstream fin("k.in");
ofstream fout("k.out");
const int inf=1<<20;
int n,m,A[100][100],P[100];
void citire()
{ int i,j,k,c;
fin>>n>>m;
for(i=1;i<n;i++)
for(j=i+1;j<=n;j++)
A[i][j]=A[j][i]=inf;
for(int k=1;k<=m;k++)
{ fin>>i>>j>>c;
A[i][j]=A[j][i]=c;
}
}
int main()
{
int i,k,minn,x;
citire();
for(i=2;i<=n;i++) P[i]=1;
for(k=1;k<n;k++)
{
minn=inf;
for(i=1;i<=n;i++)
if(P[i] && A[P[i]][i]<minn)
{
minn=A[P[i]][i]; x=i;
}
fout<<P[x]<<" "<<x<<" "<<A[P[x]][x]<<endl;
for(i=1;i<=n;i++)
if(P[i] && A[P[i]][i]>A[i][x])
P[i]=x;
P[x]=0;
}
fin.close();
fout.close();
return 0;
}
|