|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 447908543 于 2019-6-27 14:40 编辑
百炼1251:丛林中的路,http://bailian.openjudge.cn/practice/1251/,我用prim算法写的c程序,一直提示Runtime Error,我是真的不知道错在哪了,大家救救孩子吧
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <stdbool.h>
- typedef struct
- {
- int vexnum;
- int **arc;
- }G;
- typedef struct
- {
- int name;//终站
- int min;
- }Prim;
- int color[30];
- G *Init(int n)
- {
- G *p=(G *)malloc(sizeof(G));
- p->vexnum=n;
- p->arc=(int **)malloc(sizeof(int*)*p->vexnum);
- for(int i=0;i<p->vexnum;i++)
- {
- p->arc[i]=(int *)malloc(sizeof(int)*p->vexnum);
- }
- for(int i=0;i<p->vexnum;i++)
- {
- for(int j=0;j<p->vexnum;j++)
- {
- p->arc[i][j]=0;
- }
- }
-
- char cstart,cend;
- int way,power;
- for(int i=0;i<p->vexnum-1;i++)
- {
- scanf("%c",&cstart);
- getchar();
- scanf("%d",&way);
- getchar();
- while(way--)
- {
- scanf("%c",&cend);
- getchar();
- scanf("%d",&power);
- getchar();
- p->arc[cstart-'A'][cend-'A']=power;
- p->arc[cend-'A'][cstart-'A']=power;
- }
- }
- return p;
- }
- void Create_t(G *graph,Prim *t)
- {
- int min;
- for(int i=0;i<graph->vexnum;i++)
- {
- min=100;
- for(int j=0;j<graph->vexnum;j++)
- {
- if(graph->arc[i][j]&&graph->arc[i][j]<min&&!color[j])
- {
- min=graph->arc[i][j];
- t[i].name=j;
- }
- }
- t[i].min=min;
- }
-
- }
- void PrimInit(G *graph)
- {
- int num=graph->vexnum;
- Prim *t=(Prim *)malloc(sizeof(Prim)*graph->vexnum);
- int index,cost=0;
- color[0]=1;
- while(--num)
- {
- Create_t(graph,t);
- int min=100;
- for(int i=0;i<graph->vexnum;i++)
- {
- if(color[i]==1&&min>t[i].min&&!color[t[i].name])
- {
- min=t[i].min;
- index=i;
- }
- }
- color[t[index].name]=1;
- cost+=min;
- graph->arc[index][t[index].name]=100;
- graph->arc[t[index].name][index]=100;
- }
- printf("%d\n",cost);
- }
- void Init_color()
- {
- for(int i=0;i<30;i++)
- {
- color[i]=0;
- }
- }
- void end(G *graph)
- {
- for(int i=0;i<graph->vexnum;i++)
- {
- free(graph->arc[i]);
- }
- free(graph);
- }
- int main(void)
- {
- int n;
- scanf("%d",&n);
- while(n)
- {
- fflush(stdin);
- Init_color();
- G *graph=Init(n);
- PrimInit(graph);
- scanf("%d",&n);
- end(graph);
- }
- return 0;
- }
复制代码 |
|