# 编程的乐趣

422人阅读 评论(0)

#include "stdio.h"
#include  "stdbool.h"
#define   NUM   5
#define    INF  9999

bool is_all_in(int set[],int n);
void path0to(int v,int path0[]);
void dist0to(int v,int dist0[]);

struct stack{
int a[100];
int top;
}

main()
{
int n;
n = NUM;
int ei[(NUM-1+1)*(NUM-1)/2]={16,2,8,INF,12,INF,5,3,4,9};
int E[NUM][NUM];
int i,j,k;
for(i=0;i<n;i++)
E[i][i] = 0;
k=0;
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
E[i][j] = ei[k++];

for(j=0;j<n-1;j++)
for(i=j+1;i<n;i++)
E[i][j] = E[j][i];
printf("the edge matrix following\n\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if( j == n-1 )
printf("%-4d\n\n",E[i][j]);
else
printf("%-4d ",E[i][j]);
int dist0[n];
int set[n];
for(i=0;i<n;i++)
set[i] = 0;
for(i=0;i<n;i++)
dist0[i] = E[0][i];
int path0[n];
for(i=0;i<n;i++)
path0[i] = -1;
set[0] = 1;
path0[0] = 0;
while(!is_all_in(set,n))
{
int min;
min = INF;
k = 0;
for(i=0;i<n;i++)
if( dist0[i] < min && set[i] == 0 )
{min = dist0[i];
k = i;}
set[k] = 1;
for(j=0;j<n;j++)
if( dist0[k]+E[k][j] < dist0[j] )
{dist0[j] =dist0[k] + E[k][j];
path0[j] = k;}
}
printf("the path state below\n\n");
for(i=0;i<n;i++)
printf("%-2d ",i);
putchar('\n');
for(i=0;i<n;i++)
printf("%-2d ",path0[i]);
putchar('\n');
dist0to(1,dist0);
path0to(1,path0);
}
bool is_all_in(int set[],int n)
{
int i;
for(i=0;i<n;i++)
if( set[i] ==0 )
return false;
return true;

}
void path0to(int v,int path0[])
{
printf("the shortest path from 0 to %d is \n",v);
printf("%d ",0);
struct stack s;
s.top = -1;
while ( path0[v] != -1 )
{s.a[++s.top] = v;
v = path0[v];}
s.a[++s.top] = v;
while(s.top >= 0)
printf("%d ",s.a[s.top--]);
}
void dist0to(int v,int dist0[])
{
printf("the shortest length from 0 to %d is \n%d\n",v,dist0[v]);
}

int E[NUM][NUM];
int i,j,k;
for(i=0;i<n;i++)
E[i][i] = 0;

k=0;
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
E[i][j] = ei[k++];

for(j=0;j<n-1;j++)
for(i=j+1;i<n;i++)
E[i][j] = E[j][i];

<未完待续>

个人资料
等级：
访问量： 6万+
积分： 1223
排名： 4万+
最新评论