用數組模擬鏈表實現鄰接表的妙用

圖例

在這裏插入圖片描述

代碼

#include<bits/stdc++.h>
using namespace std;
//Head 與 next 數組存儲的是ver數組的下標,0表示指向空
//ver 數組存儲的是每條邊的終點
//使用數組實現鄰接表,無向圖
const int N = 1010;   //頂點數
const int M = 10100;  //邊數
int head[N],Next[2*M],ver[2*M],dist[2*M],tot=-1;
void add(int x,int y,int z)
{
    ver[++tot] = y;    //這條邊到達的點
    Next[tot] = head[x];  //鏈接
    head[x] = tot;    //標記x起點
    dist[tot] = z;  //權值
}
void printU(int u)
{
    //! 訪問從u出發的所有邊,當next[i]=0時遍歷結束
    cout<<u<<":";
    for(int i=head[u];i;i=Next[i]){
        int v = ver[i];
        int d = dist[i];
        cout<<"("<<u<<","<<v<<","<<d<<")";
    }
}
int main()
{
    add(1,2,77);
    add(2,3,777);
    add(2,5,77777);
    add(3,5,77777);
    add(5,4,7777);
    add(5,1,7);
    for(int u=1;u<=5;u++){
        printU(u);
        cout<<endl;
    }
    return 0;
}

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章