邻接表的数组实现
#include<bits/stdc++.h>
#define INF 0x3f3f3f3f3f3f3f3f
#define mod 1000000007
#define IOS ios::sync_with_stdio(false)
#define endl '\n'
using namespace std;
typedef long long ll;
const int maxn = 1e5 + 10;
int first_edge[maxn], next_edge[maxn];
int u[maxn], v[maxn], w[maxn];
int n, m;
void init(){
for (int i = 1;i <= n;++i)first_edge[i] = -1;//初始化为-1代表顶点1~n暂时没有边
}
void get_edge() {
int k = 0;
for (int i = 1;i <= n;++i) {//枚举每个顶点
k = first_edge[i];//k为顶点i的第一条边的编号
while (k != -1) {
printf("%d %d %d\n", u[k], v[k], w[k]);
k = next_edge[k];//k为顶点i下一条边的编号
}
}
}
int main() {
cin >> n >> m;//n个顶点m条边
init();
for (int i = 1;i <= m;++i) {
cin >> u[i] >> v[i] >> w[i];//边u[i]到v[i]的权值为w[i];
//关键
next_edge[i] = first_edge[u[i]];//编号为i的边的下一条边
first_edge[u[i]] = i;//顶点u[i]的第一条边编号为i
}
get_edge();
}
邻接表的链表实现