图的存储(1)---邻接矩阵和邻接表的学习

在图论中,一般都要先把图的信息存起来,然后在运用算法去解题,在这一篇博客中,我只说两种存图方式,一个是邻接矩阵,另一个是邻接表;还有两种存图方式在下一篇博客给大家具体说。

邻接矩阵:它的优点是好写,但是效率在数据达到1000以上就会超过1s的时间,所以要针对题目所给要求,来选择合适的存图方式。

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 1010;
const int INF = 0x3f3f3f3f;
int Map[maxn][maxn];
int n, m;

void init() {
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= n; j++) {
			if (i == j)Map[i][j] = 0;
			else Map[i][j] = INF;
		}
	}
}

void input() {
	int u, v, w;
	for (int i = 0; i < m; i++) {
		cin >> u >> v >> w;
		if (Map[u][v] > w)
			Map[u][v] = Map[v][u] = w;
	}
}

void output() {
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= n; j++) {
			printf("%d", Map[i][j]);
		}cout << endl;
	}
}

int main() {
	cin >> n >> m;
	init();
	input();
	output();
	return 0;
}

邻接表看我下一篇的链式前向星

 

posted @ 2018-04-04 20:13  lived  阅读(282)  评论(0编辑  收藏  举报