静态邻接表

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

 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).

转载于:https://www.cnblogs.com/ZQUACM-875180305/p/8626707.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值