First Strike prim algorithm
Code that saved the path: Lowcost and MST are not merged
#include <cstdio>
#include <string.h>
Prim
const int maxn=2010;
const int inf=10000;
int LOWCOST[MAXN],MST[MAXN];
int MAP[MAXN][MAXN];
int n,m;
Char str[maxn][10];
void Prim (int u0)//From
{
int i,j;
int ans=0;
for (I=1; i<=n; ++i)
lowcost[i]=map[u0][i],mst[i]=u0;
Mst[u0]=-1;
for (I=1; i<n; ++i)
{
int min=inf;
int v=-1;
for (j=1; j<=n; ++j)
if (mst[j]!=-1 && lowcost[j]<min)//Find MST not 1 and lowcost the smallest edge
V=j, Min=lowcost[j];
if (v!=-1)
{
printf ("%d%d%d\n", v,mst[v],lowcost[v]);
mst[v]=-1;//V is added to T
ANS+=LOWCOST[V];
for (j=1; j<=n; ++j)
if (Mst[j]!=-1 && map[v][j]<lowcost[j])//update the newly added V with the original point of the shortest
Lowcost[j]=map[v][j],mst[j]=v;
}
}
printf ("The highest possible quality is 1/%d.\n", ans);
}
int main ()
{
int i,j,k;
int u,v,w;
while (scanf ("%d", &n)!=eof && N)
{
memset (map, 0, sizeof (map));
for (I=1; i<=n; ++i)
{
scanf ("%s", str+i);
}
for (I=1; i<=n; ++i)
for (j=i; j<=n; ++j)
{
if (i==j) map[i][j]=0;
Else
{
for (k=0; k<7; ++k)
if (Str[i][k]!=str[j][k]) ++map[i][j];
MAP[J][I]=MAP[I][J];
}
}
Prim (1);
}
return 0;
}
Ways to not save paths:
#include <cstdio>
#include <string.h>
Prim
const int maxn=2010;
const int inf=10000;
int MST[MAXN];
int MAP[MAXN][MAXN];
int n,m;
Char str[maxn][10];
void Prim (int u0)//
{
int i,j;
int ans=0;
for (I=1; i<=n; ++i)
Mst[i]=map[u0][i];
Mst[u0]=-1;
for (I=1; i<n; ++i)
{
int min=inf;
int v=-1;
for (j=1; j<=n; ++j)
if (mst[j]!=-1 && mst[j]<min) v=j, min=mst[j];
if (v!=-1)
{
printf ("%d%d%d\n", v,mst[v],lowcost[v]);
ANS+=MST[V];
mst[v]=-1;//V is added to T
for (j=1; j<=n; ++j)
if (Mst[j]!=-1 && map[v][j]<mst[j])//update the newly added V with the original point of the shortest
MST[J]=MAP[V][J];
}
}
printf ("The highest possible quality is 1/%d.\n", ans);
}
int main ()
{
int i,j,k;
int u,v,w;
while (scanf ("%d", &n)!=eof && N)
{
memset (map, 0, sizeof (map));
for (I=1; i<=n; ++i)
{
scanf ("%s", str+i);
}
for (I=1; i<=n; ++i)
for (j=i; j<=n; ++j)
{
if (i==j) map[i][j]=0;
Else
{
for (k=0; k<7; ++k)
if (Str[i][k]!=str[j][k]) ++map[i][j];
MAP[J][I]=MAP[I][J];
}
}
Prim (1);
}
return 0;
}
2 methods There's no big difference in time.