Truck History--POJ 1789

1、题目类型:图论、最小生成树、Prim算法。

2、解题思路:(1)将输入转换为map[][]:即匹配任意两个字符串,记录其不同的字母个数;(2)Prim算法求解最小生成树。

3、注意事项:Prim算法的简单应用。

4、实现方法:

  
    
#include < iostream >
#include
< algorithm >
using namespace std;
#define Max 100000

int n,map[ 2010 ][ 2010 ];
bool vis[ 2010 ];
char str[ 2010 ][ 8 ];

int Distance( char str1[], char str2[])
{
int i,cnt = 0 ;
for (i = 0 ;i < 8 ;i ++ )
{
if (str1[i] != str2[i])
cnt
++ ;
}
return cnt;
}

int Prim()
{
int i,j,pos,ans = 0 ,dis[ 2010 ];
memset(vis,
0 , sizeof (vis));

for (i = 0 ;i < n;i ++ )
dis[i]
= map[ 0 ][i];
vis[
0 ] = 1 ;

for (i = 0 ;i < n - 1 ;i ++ )
{
pos
= min_element(dis + 1 ,dis + n) - dis;
vis[pos]
= 1 ;
ans
+= dis[pos];
dis[pos]
= Max;

for (j = 0 ;j < n;j ++ )
if ( ! vis[j] && dis[j] > map[pos][j])
dis[j]
= map[pos][j];
}
return ans;
}

int main()
{
int i,j,ans;
while (cin >> n && n)
{
for (i = 0 ;i < n;i ++ )
{
cin
>> str[i];
for (j = i - 1 ;j >= 0 ;j -- )
map[i][j]
= map[j][i] = Distance(str[i],str[j]);
}
ans
= Prim();
cout
<< " The highest possible quality is 1/ " << ans << " . " << endl;
}
return 1 ;
}

 

你可能感兴趣的:(history)