图知识小结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;
}


  

将上面的测试图(有向图)数据输入:

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值