这道题提交了N次,终于AC了,哪里错了呢???我一直找代码的错误。后来错误原因让我大吃一惊:我误以为题目中每一个case后都有一个0的,原来是全部case后边有一个0。。。。。
Problem: 1789 | User: qq1203456195 | |
Memory: 15892K | Time: 485MS | |
Language: C | Result: Accepted |
#include <stdio.h> #include <string.h> #define N 2002 int n;//number of truck 2..2000 char truck[N][7];//different types of truck int M[N][N];//distance between 2 trucks int lowcost[N];//辅助数组 int visited[N];//记录是否被放进最小生成树中 int dis(int i,int j)//计算i,j类truck的不同 { int k,c=0; for (k=0;k<7;k++) if(truck[i][k]!=truck[j][k]) c++; return c; } int min_lowcost(int *m) { int i,t; for (i=0;i<n;i++) if (!visited[i]&&lowcost[i]<(*m)) { t=i; (*m)=lowcost[i]; } return t; } int Prim() { int i,mindis=0,next_idx,j,next_len; for (i=0;i<n;i++) { visited[i]=0; lowcost[i]=M[0][i];//和衍生图中距离最近的那个点的距离 } visited[0]=1; for (i=1;i<n;i++)//将其余n-1辆车放入衍生图 { next_len=8; next_idx=min_lowcost(&next_len);//找出花费最小的车next mindis+=next_len;//最小生成树累加 visited[next_idx]=1;//添加到衍生图 for (j=0;j<n;j++)//更新辅助数组 { if(!visited[j]&&M[next_idx][j]<lowcost[j]) lowcost[j]=M[next_idx][j]; } } return mindis; } int main() { int i,j; while(scanf("%d",&n)!=EOF) { if (n==0) break; //read info memset(truck,0,sizeof(truck)); for (i=0;i<n;i++) scanf("%s",truck[i]); //init Metric memset(M,8,sizeof(M)); for (i=0;i<n;i++) for (j=i+1;j<n;j++) M[i][j]=M[j][i]=dis(i,j); //output result printf("The highest possible quality is 1/%d.\n",Prim()); } return 1; }