在图论中,一般都要先把图的信息存起来,然后在运用算法去解题,在这一篇博客中,我只说两种存图方式,一个是邻接矩阵,另一个是邻接表;还有两种存图方式在下一篇博客给大家具体说。
邻接矩阵:它的优点是好写,但是效率在数据达到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;
}
邻接表看我下一篇的链式前向星