图的存储(2)---链式前向星的学习

本文的来源

对链式的原理的很好的图解

我对前向星的理解是:其实就是邻接表的另外一种表示方式,思想是一样的。

学过数据结构的都知道图有两种存储方式,一种是邻接表,另一种是邻接矩阵,其实还有一种是前向星,而链式前向星是在前向星基础上优化后的。

邻接表:效率高不好写;

邻接矩阵:好写效率低;

前向星:它是基于邻接表和邻接矩阵之间的;

链式前向星:好写效率相对前向星要好多;

先写前向星:构造方法,就是把每条边的起点,终点,边权存入数组中,在进行排序,就行了。但是一个排序却需要至少也要来个快排(O(nlogn)),但是链式前向星却不需要排序,就省下了排序的时间。

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 1010;
int n,m;
int first[maxn];//头结点 
struct node{
	int u;//起点 
	int v;//终点 
	int w;//边权 
}a[maxn];

bool cmp(node p,node q){
	if(p.u==q.u)return p.v<q.v;
	else return p.u<q.u;
}

int main(){
	cin>>n>>m;
	for(int i=0;i<m;i++){
		cin>>a[i].u>>a[i].v>>a[i].w;
	}
	sort(a,a+m,cmp);
	memset(first,-1,sizeof(first));//初始化 
	first[a[0].u]=0;
	for(int i=0;i<m;i++){
		if(a[i].u!=a[i-1].u)
			first[a[i].u]=i;
	}
	for(int i=1;i<n;i++){
		for(int k=first[i];a[i].u==i&&k<m;k++){
			printf("%d %d %d\n",a[k].u,a[k].v,a[k].w);
		}
	}
	return 0;
}

接下来是链式的写法

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
const int maxn = 1010;
int n, m, k;
int first[maxn];
struct node {
	int next;//与第i条边同起点的下一条边的位置
	int v;//第i条边的终点
	int w;//第i条边的边权
}a[maxn];

void init() {
	memset(first, -1, sizeof(first));
	k = 0;
}

void add(int u, int v, int w) {
	a[k].w = w;//边权
	a[k].v = v;
	a[k].next = first[u];
	first[u] = k++;
}

void input() {
	int u, v, w;
	for (int i = 0; i<m; i++) {
		cin >> u >> v >> w;
		add(u, v, w);//加边
	}
}

void output() {
	for (int i = 0; i < k; i++) {
		printf("%d %d %d\n", a[i].next, a[i].v, a[i].w);
	}
}

int main() {
	cin >> n >> m;
	init();//初始化
	input();//输入
	output();//输出
	return 0;
}

 

 

 

 

posted @ 2018-04-03 19:47  lived  阅读(127)  评论(0)    收藏  举报