关于图的表示
对于图 G=(V,E) ,可以用两种标准的表示方法表示,一种表示方法将图作为邻接链表的组合,另一种表示法则将图作为邻接矩阵来表示。两种表示方法都可以表示无向图和无向图。当图为稀疏图时( |E|<<|V2| ),通常采用邻接链表,如此节省空间开销;反之,当图为稠密图时( |E| 接近于 |V2| ),则采用邻接矩阵。此外,如果需要直接判断任意两个结点之间是否有边连接,可能也要用邻接矩阵。
图
G=<V,E>
的邻接链表是由一个包含
|V|
个链表的数组
Adj
所组成,其中每个链表对应于
V
中的一个顶点。对于每一个
如果 G 是一个有向图,则所有邻接表的长度之和为|E|,这是因为一条形如
(u,v) 的边是通过让v出现在 Adj[u] 中来表示的。如果 G 是一个无向图,则所有邻接表的长度之和为
2|E| ,因为如果 (u,v) 是一条无向边,那么 u 会出现在v 的邻接表中,反之亦然。邻接表需要的存储空间为 O(V+E) 。邻接表稍作变动,即可用来表示加权图,即每条边都有着相应权值的图,权值通常由加权函数 w:E→R 给出。例如,设 G=<V,E> 是一个加权函数为w的加权图。对每一条边 (u,v)∈E ,权值 w(u,v) 和顶点 v 一起存储在
u 的邻接表中。
邻接链表C++实现
#include <iostream>
#include <vector>
using namespace std;
#define max 100
int Vnum, Enum;
/*
* 边结点
*/
struct EdgeNode {
int vertex;
int weight = 0;
EdgeNode * next;
EdgeNode(){}
EdgeNode(int v, int w):vertex(v), weight(w),next(NULL) {}
EdgeNode(int v):vertex(v), next(NULL) {}
};
/*
* 顶点结点
*/
struct VNode {
int vertex; //顶点编号
EdgeNode *link;//与该顶点连接的链表
}V[max];
/*
* 初始化结点
*/
void Initialize() {
for(int i = 1; i <= Vnum; i++) {
V[i].vertex = i;
V[i].link = NULL;
}
}
/*
* 结点插入
*/
void insert(int pre, int ver, int w) {
EdgeNode * ptr = new EdgeNode(ver, w);
if(V[pre].link == NULL) {
V[pre].link = ptr;
} else {
EdgeNode * tmp = V[pre].link;
//去重边
if(tmp->vertex == ver) {
if(tmp->weight != w) {
tmp->weight = w;
return;
}
}
//去重边
while(tmp->next != NULL) {
if(tmp->vertex == ver) {
if(tmp->weight != w) {
tmp->weight = w;
return;
}
}
tmp = tmp->next;
}
tmp->next = ptr;
}
}
/*
* 删除某条边
*/
void Delete(int pre, int cur) {
EdgeNode * ptr = V[pre].link;
if(ptr->vertex == cur) {
V[pre].link = ptr->next;
delete ptr;
return;
}
while(ptr->next != NULL) {
if(ptr->vertex == cur) {
V[pre].link = ptr->next;
delete ptr;
return;
}
}
}
/*
* 打印邻接表
*/
void display() {
for(int i = 1; i <= Vnum; i++) {
cout << V[i].vertex;
EdgeNode * ptr = V[i].link;
while(ptr->next != NULL) {
cout << "-> (" << ptr->vertex << ","
<< ptr->weight << ")";
ptr = ptr->next;
}
cout << "->NULL" << endl;
}
}
int main() {
int a, b, w;
cout << "enter Vnum and Enum:" << endl;
cin >> Vnum >> Enum;
Initialize();
while(Enum--) {
cin >> a >> b >> w;
//无向图
insert(a, b, w);
insert(b, a, w);
}
display();
return 0;
}