静态邻接表

有时候,二维数组开不了那么大,动态的构建邻接表容易出错,此时需要借助静态邻接表。

 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <string.h>
 4 #include <queue>
 5 using namespace std;
 6 const long edge_maxn = 1005;  //边的最大上限
 7 const long point_maxn = 105;  //点的最大上限
 8 struct node
 9 {/*node存储边,一个edge代表一条边*/
10     int v;  //终点位置
11     int w;  //权值
12     int next;  //同一起点的下一条边存储在edge数组中的位置(理解了这个静态邻接表就可以了)
13 }edge[edge_maxn];
14 int pre[point_maxn];  //以该点为起点的第一条边存储在edge数组中的位置
15 int n; //点的数量
16 int m; //边的数量
17 void Init()
18 {
19     memset(pre,-1,sizeof(pre));
20     int Index = 1;
21     int i,x,y,w;
22     for(i=0;i<m;i++)
23     {
24         scanf("%d%d%d",&x,&y,&w);
25 
26         edge[Index].v = y;
27         edge[Index].w = w;
28         edge[Index].next = pre[x];  //保存x起点的上一条边在edge数组中的位置
29         pre[x] = Index++;  //位置更新
30     }
31 }
32 void print()
33 {
34     for(int i=1;i<=n;i++)
35     {
36         printf("%d ",i);
37         for(int j=pre[i];j!=-1;j=edge[j].next)
38         {
39             printf(" -> %d value is %d ",edge[j].v,edge[j].w);
40         }
41         printf("\n");
42     }
43 }
44 int main()
45 {
46     while(scanf("%d%d",&n,&m)!=EOF && (n!=0 || m!=0))
47     {
48         Init();
49         print();
50     }
51     return 0;
52 }
View Code

静态邻接表关键是next与pre数组的构造。让我想起了关于kmp,next数组的构造,树状数组,dijkstr借东风的构造。这些构造都相互链接,互相关联,变化万千奇妙无穷啊!!!(话说,树状数组又忘了,qwq).

posted @ 2018-03-22 21:09  flyer_duck  阅读(273)  评论(0编辑  收藏  举报