静态邻接表

                    静态邻接表

 用于保存每个点出发的边。

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