输入: 输出:
6 5
4 3 90 1 5 20
1 4 30 5 2 70
5 6 60 5 6 60
1 5 20 1 4 30
5 2 70 4 3 90
知识点:链式前向星围绕边的信息存储,记录边的终点,下一条边以及其他信息
struct b{end,next,其他};记录起点所连接的边号head[x];以及记录边号cnt;
#include <iostream>
#include <cstring>
using namespace std;
//边的数据
struct bian{
//终点,下一条边,其他条件
int end,next;
int num;
//哪一条边 -> 保存的数据
}b[105];
//哪个起点 -> 现在连接的边
int h[105];
//边的编号/数目
int cnt;
//加边操作
int add(int start,int end,int num){
b[cnt].end=end;
//记录上一次的边
b[cnt].next=h[start];
b[cnt].num=num;
//记录该边
h[start]=cnt;
cnt++;
}
//遍历
int dfs(int now,int fa){
for(int i=h[now];~i;i=b[i].next){
int start=now,end=b[i].end,num=b[i].num;
if(fa==end) continue;
cout<<start<<" "<<end<<" "<<num<<endl;
dfs(end,now);
}
}
int main(){
int n,m;
cin>>n>>m;
//必须要初始化
memset(h,-1,sizeof(h));
for(int i=1;i<=m;i++){
int a,b,c;
//有向图,实现双向要两方都加
cin>>a>>b>>c;
add(a,b,c);
add(b,a,c);
}
dfs(1,0);
}