邻接表的数组写法

可以利用数组模拟链表,将从同一个结点出发的有向边建在同一个链表中

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 typedef long long ll;
 4 typedef unsigned long long ull;
 5 #define INF 0x3f3f3f3f
 6 const ll MAXN = 200 + 7;
 7 const ll MAXM = 1e3 + 7;
 8 const ll MOD = 1e9 + 7;
 9 const double pi = acos(-1);
10 int n, m; //结点,边数
11 struct Edge
12 {
13     int from, to, val;
14     int next;
15 } E[MAXM];
16 int cnt = -1;
17 int head[MAXN];
18 void add(int from, int to, int val)
19 {
20     E[++cnt].from = from;
21     E[cnt].to = to;
22     E[cnt].next = head[from];
23     head[from] = cnt;
24 }
25 int main()
26 {
27     memset(head, -1, sizeof(head));
28     cin >> n >> m;
29     for (int i = 0; i < m; i++)
30     {
31         int u, v, val;
32         cin >> u >> v >> val;
33         add(u, v, val); //建边
34     }
35     int x = 1; //遍历从结点1出发的所有有向边
36     for (int i = head[x]; i != -1; i = E[i].next)
37         printf("from=%d to=%d v=%d\n",E[i].from,E[i].to,E[i].next);
38     return 0;
39 }

猜你喜欢

转载自www.cnblogs.com/graytido/p/10883731.html