算法导论25(所有结点对的最短路径问题)

25.1最短路径和矩阵乘法

#include    
using namespace std;  
#define n 20   
int L[n][n],M[n][n];  
typedef struct    
{   
    int VNum,ENum;  
    int w[n][n];  
}Graph;    
  
void create_graph(Graph &G)    
{    
    int i,j,v1,v2;    
    cin>>G.VNum>>G.ENum;  
    for(i=0;i>v1>>v2>>j;    
        G.w[v1][v2]=j;  
    }    
}    
  
int min(int a,int b)  
{  
    return a
#include  
using namespace std;
#define n 20 
int L[n][n],M[n][n];
typedef struct  
{ 
    int VNum,ENum;
    int w[n][n];
}Graph;  

void create_graph(Graph &G)  
{  
    int i,j,v1,v2;  
    cin>>G.VNum>>G.ENum;
    for(i=0;i>v1>>v2>>j;  
		G.w[v1][v2]=j;
    }  
}  

int min(int a,int b)
{
    return a
25.2Floyd-Warshall算法

#include    
using namespace std;  
#define n 20   
int d[n][n];  
typedef struct    
{   
    int VNum,ENum;  
    int w[n][n];  
}Graph;    
  
void create_graph(Graph &G)    
{    
    int i,j,v1,v2;    
    cin>>G.VNum>>G.ENum;  
    for(i=0;i>v1>>v2>>j;    
        G.w[v1][v2]=j;  
    }    
}    
  
int min(int &a,int &b)  
{  
    return a

25.3用于稀疏图的Johnson算法

#include  
using namespace std;
#define n 20 
int dist1[n],dist2[n],d[n],D[n][n];

typedef struct ENode  
{ 
    int v,w;
    ENode *next;
}ENode;  
typedef struct VNode
{
    int u;
    ENode *next;
}VNode;
typedef struct
{
    int VNum,ENum;
    VNode Adj[n];
}Graph;

void create_graph(Graph &G)  
{  
    int i,j,v1,v2;  
    cin>>G.VNum>>G.ENum;
    for(i=0;i>v1>>v2>>j;
        ENode *p=(ENode *)malloc(sizeof(ENode));
        p->v=v2;
        p->w=j;
        p->next=G.Adj[v1].next;
        G.Adj[v1].next=p;
    }  
}  

void initialize_single_source1(Graph G,int s)  
{  
    for(int i=0;iv,p->w);  
                p=p->next;  
            }  
        }  
    }  
    for(j=0;jwv])return false;  
            p=p->next;  
        }  
    }  
    return true;  
}  

void initialize_single_source2(Graph G,int s)  
{  
    for(int i=0;iv,p->w);  
            p=p->next;  
        }  
    }  
}  

void Johnson(Graph G)
{
    int i,j;
    Graph H=G;
    H.Adj[G.VNum].u=G.VNum;
    H.Adj[G.VNum].next=NULL;
    for(i=0;iv=i;
        p->w=0;
        p->next=H.Adj[G.VNum].next;
        H.Adj[G.VNum].next=p;
    }
    H.VNum++;
    if(!Bellman_Ford(H,G.VNum))cout<<"the input graph contains a negative-weight cycle"<w=p->w+dist1[i]-dist1[p->v];
                p=p->next;
            }
        }
        H.VNum--;
        for(i=0;i




你可能感兴趣的:(算法导论)