POJ1789(Prim算法)

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

char str[2000][8];
int edge[200][200];
int d[20000];

int get_dis(char *str1,char *str2)
{
	int i;
	int ans=0;

	for (i=0;i<=6;i++)
		if (str1[i]!=str2[i])
			ans++;
	return ans;
}

int main()
{
	int n;
	const int maxn=1000000000;
	while (1)
	{
		memset(edge,0,sizeof(edge));
		memset(d,0,sizeof(d));
		scanf("%d",&n);
		if (!n)
			break;

		int i,j;

		for (i=0;i<=n-1;i++)
			d[i]=maxn;
		for (i=0;i<=n-1;i++)
			scanf("%s",str[i]);

		for (i=0;i<=n-1;i++)
			for (j=i+1;j<=n-1;j++)
				edge[i][j]=edge[j][i]=get_dis(str[i],str[j]);

		//Prim
		int ans=0;
		int pos;
		int min;
		bool record[2000]={false};
		d[0]=0;
		for (i=0;i<=n-1;i++)
		{
			min=maxn;
			for (j=0;j<=n-1;j++)
				if (!record[j] && d[j]<min)
				{
					pos=j;
					min=d[pos];
				}
			if (min==maxn)
				continue;
			ans+=min;
			record[pos]=true;
			for (j=0;j<=n-1;j++)
				if (!record[j] && edge[pos][j]<d[j])
					d[j]=edge[pos][j];
		}

		printf("The highest possible quality is 1/%d.\n",ans);
	}
	return 0;
}

你可能感兴趣的:(POJ1789(Prim算法))