链式向前星

有时图用邻接矩阵存太浪费时,就会用邻接表,一般来说用vector存更方便,但是vector太慢,如果数据太大容易TLE,这时就用链式向前星,相当于链表。

 1 #include <iostream>
 2 #include <cstring>
 3 #include <algorithm>
 4 using namespace std;
 5 struct sdfd
 6 {
 7     int from,to,n;//from代表与此边相同起点的另一条边在zz数组中的位置
 8     //to代表这条边的终点,n代表这条边的权值
 9 }zz[5555];
10 int sb[3535];//sb[i]代表从i出发的第一条边在zz数组中的位置
11 int main ()
12 {
13     memset (sb,-1,sizeof(sb));
14     memset (zz,-1,sizeof(zz));
15     int n,m;
16     cin >>n>>m;
17     for (int i=0;i<m;i++)
18     {
19         int a,b,c;
20         cin >>a>>b>>c;
21         zz[i].to=b;
22         zz[i].n=c;
23         zz[i].from=sb[a];
24         sb[a]=i;//当初不太明白sb数组的意义,结合它的使用才慢慢反应过来
25     }
26     int i;
27     cin >>i;
28     int t=sb[i];
29     while (t!=-1)
30     {
31         cout <<"from "<<i<<"to "<<zz[t].to<<"is "<<zz[t].n<<endl;
32         t=zz[t].from;
33     }
34     return 0;
35 }
36 /*
37 5 8
38 3 5 5
39 1 4 6
40 2 5 8
41 1 2 3
42 3 4 7
43 2 3 9
44 1 5 7
45 1
46 */
View Code

ps:或许把sb[i]看做从i出发的最后一条边比较好理解。。。。。。

参考博客:https://blog.csdn.net/u013894557/article/details/22512747

猜你喜欢

转载自www.cnblogs.com/abc1604831024/p/8907805.html