最短路径Floyd算法

来源:互联网 发布:数据挖掘软件容易使用 编辑:程序博客网 时间:2024/06/03 20:30
#include<stdio.h>struct Dist{    int length;    int pre;};typedef struct Dist dist[4][4];struct ArcCell{    int data;};typedef struct ArcCell arccell;typedef struct ArcCell arc[4][4];typedef struct {    int a[4];    arc ar;    int vexnum;    int arcnum;}MGraph;MGraph CreateMGraph(MGraph m){    scanf("%d%d",&m.vexnum,&m.arcnum);    int i,j;    for(i=0;i<m.vexnum;i++) scanf("%d",&m.a[i]);    for(i=0;i<m.vexnum;i++)        for(j=0;j<m.vexnum;j++)            m.ar[i][j].data = 10;    for(i=0;i<m.arcnum;i++){        int v1,v2,w;        scanf("%d%d%d",&v1,&v2,&w);        m.ar[v1][v2].data = w;    }    return m;}void Floyd(MGraph m,dist d){    int i,j,k;    for(i=0;i<m.vexnum;i++)    for(j=0;j<m.vexnum;j++){        d[i][j].length = m.ar[i][j].data;        d[i][j].pre = i;    }    for(k=0;k<m.vexnum;k++)    for(i=0;i<m.vexnum;i++)    for(j=0;j<m.vexnum;j++){       if(d[i][j].length>d[i][k].length+d[k][j].length){            d[i][j].length = d[i][k].length+d[k][j].length;            d[i][j].pre = k;       }    }}void pre(dist d,int i ,int j){//打印中间节点    if(i!=d[i][j].pre){        printf("%d",d[i][j].pre);        j = d[i][j].pre;        pre(d,i,j);    }}int main(){    MGraph m;    MGraph n = CreateMGraph(m);    dist d;    Floyd(n,d);    pre(d,0,1);    //printf("%d",n.ar[1][2].data);}
  1. 动态规划的典型实例