图知识小结6-十字链表的数组实现与应用
十字链表是一种高效存储稀疏图并可以显著提高查找效率的一种存储结构,解决了图的遍历过程中邻接表空间消耗大而邻接矩阵求一个点入度又需要遍历全部表的问题,下面给出其数组实现:
//十字链表的数组实现
#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;
}
将上面的测试图(有向图)数据输入: