用邻接表一直WA,只好改用邻接矩阵。
贴代码
#include<iostream>
#include<vector>
#include<queue>
#include<string>
using namespace std;
char str[2010][8];
int mark[2010]; //标记是否访问过,访问过为1,否则为0
int map[2002][2002];
int n;
class Dist
{
public:
int pre;
int length;
int index;
friend bool operator<(const Dist &a,const Dist &b)
{
return a.length>b.length;
}
};
void prim(int s)
{
int ans=0;
Dist *D = new Dist[n+1];
for(int i=1;i<=n;i++)
{
D[i].index = i;
D[i].pre = s;
D[i].length = 1<<30;
}
priority_queue<Dist> aqueue;
int now_node=s;
for(int i=1;i<n;i++)
{
mark[now_node]=1;
for(int j=1;j<=n;j++)
{
if( mark[j]==0 && D[j].length>map[now_node][j])
{
D[j].length = map[now_node][j];
D[j].pre = now_node;
aqueue.push(D[j]);
}
}
Dist d;
while(!aqueue.empty())
{
d = aqueue.top();
aqueue.pop();
if(mark[d.index]==0)
break;
}
now_node = d.index;
ans = ans + d.length;
}
cout<<"The highest possible quality is 1/"<<ans<<"."<<endl;
}
int different(int s1,int s2)
{
int ans=0;
for(int i=0;i<7;i++)
{
if(str[s1][i]!=str[s2][i])
ans++;
}
return ans;
}
int main()
{
int i,j;
int weight;
while(cin>>n)
{
if(n==0)
break;
memset(mark,0,sizeof(mark));
for(i=1;i<=n;i++)
{
scanf("%s",str[i]);
}
for(i=1;i<=n;i++)
{
for(j=1;j<i;j++)
{
weight=different(i,j);
map[i][j]=map[j][i]=weight;
}
}
prim(1);
}
return 0;
}