关于链式前向星dalao在这里已经讲得很清楚了,这里就贴个板子。
#include <bits/stdc++.h>
#define ll long long
#define INF 0x3f3f3f3f
using namespace std;
const int maxe = 1e6+6;
const int maxn = 1e6+6;
struct Edge
{
int to, w, next;
Edge() {}
Edge(int to, int w, int next): to(to), w(w), next(next) {}
};
Edge edge[maxe];
int head[maxn];
int n, e;
void init()
{
for(int i = 0; i < maxn; ++i)
head[i] = -1;
}
void addEdge(int u, int v, int w, int id)
{
edge[id] = Edge(v, w, head[u]);
head[u] = id;
}
void traversal()
{
for(int i = 0; i < n; ++i)
for(int j = head[i]; ~j; j = edge[j].next) //~是按位取反,-1的二进制是111...1,按位取反后变为000...0,相当于 != -1
cout << i << " -> " << edge[j].to << endl;
}
void read()
{
cin >> n >> e;
int u, v, w;
for(int i = 0; i < e; ++i)
{
cin >> u >> v >> w;
addEdge(u, v, w, i);
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
init();
read();
traversal();
return 0;
}