chain forward star

Sometimes when the adjacency matrix is ​​too wasteful to store the graph, the adjacency list is used. Generally speaking, it is more convenient to use the vector to store, but the vector is too slow. If the data is too large, it is easy to TLE, then the chain forward star is used, which is equivalent to the linked list. .

1 #include <iostream>
 2 #include <cstring>
 3 #include <algorithm>
 4  using  namespace std;
 5  struct sdfd
 6  {
 7      int  from ,to,n; // from represents another edge with the same starting point as this edge in Position 8      in the zz array
 // to represents the end point of this edge, n represents the weight of this edge 
9 }zz[ 5555 ];
 10  int sb[ 3535 ]; // sb[i] represents the first starting point from i The position of an edge in the zz array 
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; // I didn't quite understand the meaning of the sb array at first, and it was slowly reacted with its use
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: Perhaps it is easier to understand sb[i] as the last edge from i. . . . . .

Reference blog: https://blog.csdn.net/u013894557/article/details/22512747

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324633759&siteId=291194637