邻接矩阵转换成邻接表
作者:
3include
,
2024-09-01 21:28:23
,
所有人可见
,
阅读 1
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 510, M = 100010, INF = 0x3f3f3f3f;
int n, m;
int g[N][N];
struct Node{
int id;
int w;
Node *next;
Node(int _id, int _w): id(_id), w(_w), next(NULL){}
} *head[N];
void add(int a, int b, int w) {
Node *p = new Node(b, w);
p->next = head[a];
head[a] = p;
}
void convert() {
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++)
if(g[i][j] < INF/2)
add(i, j, g[i][j]);
}
int main() {
memset(g, 0x3f, sizeof g);
cin >> n >> m;
while(m --) {
int a, b, w;
cin >> a >> b >> w;
g[a][b] = g[b][a] = min(g[a][b], w);
}
puts("邻接矩阵表示法:");
for(int i=1; i<=n; i++) {
for(int j=1; j<=n; j++)
if(g[i][j] > INF/2)
cout << '-' << ' ';
else
cout << g[i][j] << ' ';
cout << endl;
}
convert();
puts("\n邻接表表示法(括号内为权值):");
for(int i=1; i<=n; i++) {
printf("与%d相连的边有: ", i);
for(Node *p=head[i]; p ; p=p->next)
printf("%d(%d)", p->id, p->w);
cout << endl;
}
return 0;
}