[資料結構] Floyd演算法計算圖的中心點

來源:互聯網
上載者:User
#include <iostream>using namespace std; #define MAX_V 100 //定義最大頂點個數#define INF 10000 //表示正無窮 typedef struct MGraph//圖的定義{    //int matrix[MAX_V][MAX_V];//鄰接矩陣,帶權值可存權值如下     int weight[MAX_V][MAX_V];//存放權值矩陣     int v;//頂點數int e;//邊數    int vertax[MAX_V];//存放頂點資訊};//圖的鄰接矩陣類型void CreateMGragh(MGraph *G){int i,j,m,weight;cout << "請輸入頂點數和邊數:" << endl;cin >> G->v >> G->e ;cout << "請輸入頂點資訊:" << endl;for (i=1;i<=G->v;i++)  scanf("%d",&G->vertax[i]);//輸入頂點資訊,建立頂點表for (i=1;i<=G->v;i++)//初始化權值矩陣   for (j=1;j<=G->v;j++)     G->weight[i][j]=INF;//讓所有權值不存在     for(i=1;i<=G->v;i++)//是結點自身指向自身權值為0   for(j=1;j<=G->v;j++)    if(i==j)      G->weight[i][j]=0;cout << "輸入每條有向邊的首尾頂點序號及權值:" << endl;for (m=0;m<G->e;m++){cin >> i >> j >> weight;G->weight[i][j]=weight;}}void DisplayMGragh_W(MGraph *G)//輸出權值矩陣G{    int i,j;    for(i=1;i<=G->v;i++)    {        for(j=1;j<=G->v;j++)          printf("%8d",G->weight[i][j]);        printf("\n");    }}void DisplayArray(MGraph *G,int Shortest[MAX_V][MAX_V])//輸出最短路徑矩陣{    int i,j;    for(i=1;i<=G->v;i++)    {        for(j=1;j<=G->v;j++)          printf("%8d",Shortest[i][j]);        printf("\n");    }}void Floyd(MGraph *G,int Shortest[MAX_V][MAX_V]){    int i,j,k;for(i=1;i<=G->v;i++)  for(j=1;j<=G->v;j++)    Shortest[i][j]=G->weight[i][j];    for(k=1;k<=G->v;k++)      for(i=1;i<=G->v;i++)        for(j=1;j<=G->v;j++)          if(Shortest[i][k]+Shortest[k][j]<Shortest[i][j])            Shortest[i][j]=Shortest[i][k]+Shortest[k][j];        } void MaxArray(int MAX[MAX_V],int Shortest[MAX_V][MAX_V],int v){int i,j;for(i=1;i<=v;i++){  for(j=1;j<=v;j++)  {      if((MAX[i]<Shortest[j][i])&&(Shortest[j][i]!=INF))          MAX[i]=Shortest[j][i];          if(Shortest[j][i]==INF)          {          MAX[i]=INF;          break;          }  }}    for(i=1;i<=v;i++)  printf("%d ",MAX[i]);    printf("\n");}void MinPath(int MAX[MAX_V],int v){int i;int min=INF,flag=0;for(i=1;i<=v;i++)  if(min>MAX[i])  {          min = MAX[i];          flag = i;  }    cout << "中心點為:" << flag <<" "<<"最小偏心度為:" << min <<endl; }int main(){     struct MGraph *G;G = new MGraph;int Shortest[MAX_V][MAX_V]; int MAX[MAX_V];memset(MAX,0,MAX_V);int v,i,min;CreateMGragh(G);v=G->v;DisplayMGragh_W(G); cout << endl;Floyd(G,Shortest);DisplayArray(G,Shortest); MaxArray(MAX,Shortest,v);MinPath(MAX,v);delete G;return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.