邻接矩阵
#include <iostream>
using namespace std;
const int N = 520,INF=0x3f3f3f3f;
int n,m;
int g[N][N];
void init()
{
for(int i = 1;i <=n;i++)
for(int j = 1;j <= n;j++)
if(i == j) g[i][j] = 0;
else g[i][j] = INF;
}
// 5 5
// 1 2 3
// 2 4 2
// 4 5 3
// 1 3 4
// 3 4 1
int main()
{
cin>>n>>m;
init();
while(m--)
{
int x,y,w;
cin>>x>>y>>w;
g[x][y] = min(g[x][y],w);//重边
}
for(int i = 1;i <= n;i++)
{
for(int j = 1;j <= n;j++)
cout<<g[i][j]<<" ";
cout<<endl;
}
return 0;
}
邻接表
#include <bits/stdc++.h>
using namespace std;
const int N = 520,M = 520;
int n,m,head[N],idx; //head[N] 表示头节点 ,idx表示边的索引
struct{
int to,next,w;//to表示指向的节点,next表示下一条边,w表示权重
}e[M];
void init()
{
memset(head,-1,sizeof(head));
idx = 1;
}
void add_mul(int a,int b,int w)
{
e[idx].to = b;
e[idx].w = w;
e[idx].next = head[a];//头插法
head[a] = idx;
idx ++;
}
bool vis[N];
void dfs(int now)
{
vis[now] = true;
for(int i = head[now];i != -1;i = e[i].next)
{
int to = e[i].to;
int w = e[i].w;
printf("%d->%d(%d)",now,to,w);
if(vis[to]) continue;
dfs(to);
}
}
queue<int>Q;
void bfs(int now)
{
Q.push(now);
while(!Q.empty())
{
int i = Q.front();
Q.pop();
vis[i] = true;
for(int j = head[i];j != -1;j = e[j].next)
{
int to = e[j].to;
int w = e[j].w;
if(vis[to]) continue;
printf("%d->%d(%d)",i,to,w);
vis[to] = true;
Q.push(to);
}
}
}
int main()
{
cin >> n >> m;
init();
while(m--)
{
int from,to,w;
cin >> from >> to >> w;
add_mul(from,to,w);
}
bfs(1);
cout<<endl;
return 0;
}