首先给出学习的博客:链式前向星与邻接表对比
链式前向星就是一个储存图很好用的东西
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <iostream> using namespace std; #define MAXM 500010 #define MAXN 10010 struct EDGE{ int next; //下一条边的存储下标 int to; //这条边的终点 int w; //权值 }; EDGE edge[MAXM]; int n, m, cnt; int head[MAXN]; //head[i]表示以i为起点的第一条边 void Add(int u, int v, int w) { //起点u, 终点v, 权值w edge[++cnt].next = head[u]; edge[cnt].w = w; edge[cnt].to = v; head[u] = cnt; //第一条边为当前边 } void Print() { int st; cout << "Begin with[Please Input]: "; cin >> st; for(int i=head[st]; i!=0; i=edge[i].next) {//i开始为第一条边,每次指向下一条(以0为结束标志)若下标从0开始,next应初始化-1 cout << "Start: " << st << endl; cout << "End: " << edge[i].to << endl; cout << "W: " << edge[i].w << endl << endl; } } int main() { int s, t, w; while(cin >> n >> m){ for(int i=1; i<=m; i++) { cin >> s >> t >> w; Add(s, t, w); } Print(); } return 0; }