圖知識小結6-十字連結串列的陣列實現與應用
阿新 • • 發佈:2018-12-11
十字連結串列是一種高效儲存稀疏圖並可以顯著提高查詢效率的一種儲存結構,解決了圖的遍歷過程中鄰接表空間消耗大而鄰接矩陣求一個點入度又需要遍歷全部表的問題,下面給出其陣列實現:
//十字連結串列的陣列實現 #include <bits/stdc++.h> using namespace std; const int MAX_EDGE = 10000; const int MAX_VERTICES = 100; struct Edge{ int from, to, last_from, last_to, len; } edge[MAX_EDGE * 2]; //這裡預設是有向圖,開陣列大小是MAX_EDGE*2,但如果題目是無向圖,應該開MAX_EDGE*4; int eid, nv, ne; int p_from[MAX_VERTICES], p_to[MAX_VERTICES]; void init(){ eid = 0; memset(p_from, -1, sizeof(p_from)); memset(p_to, -1, sizeof(p_to)); } void insert(int w, int from, int to){ edge[eid].to = to; edge[eid].from = from; edge[eid].len = w; edge[eid].last_from = p_from[from]; //從頂點from指出的所有邊 edge[eid].last_to = p_to[to]; //指向頂點to的所有邊 p_from[from] = p_to[to] = eid++; //更新最後一次儲存的邊值 } void visit_from(int v){ //遍歷從從v指出的所有邊 for(int id = p_from[v] ; id != -1 ; id = edge[id].last_from){ cout << edge[id].to << " "; } } void visit_to(int v){ //遍歷指向v的所有邊 for(int id = p_to[v] ; id != -1 ; id = edge[id].last_to){ cout << edge[id].from << " "; } } int main(){ init(); cin >> nv >> ne; //預設為有向圖給出的實現,如果為無向圖,則需要insert兩次 int w, u, v; for(int i = 0 ; i < ne ; i++){ cin >> w >> u >> v; insert(w, u, v);//無向圖 //insert(w, v, u); 有向圖還需要加上此行 } for(int i = 1 ; i <= nv ; i++){ cout << "From " << i << " to "; visit_from(i); cout << endl; } for(int i = 1 ; i <= nv ; i++){ cout << "To " << i << " from "; visit_to(i); cout << endl; } return 0; }
將上面的測試圖(有向圖)資料輸入: