静态邻接表

#include <iostream>  
#include <queue>  
using namespace std;  
const long edge_maxn = 1005;  //边的最大上限  
const long point_maxn = 105;  //点的最大上限  
struct node  
{/*node存储边,一个edge代表一条边*/  
    int v;  //终点位置  
    int w;  //权值  
    int next;  //同一起点的下一条边存储在edge数组中的位置(理解了这个静态邻接表就可以了)  
}edge[edge_maxn];  
int pre[point_maxn];  //以该点为起点的第一条边存储在edge数组中的位置  
int n; //点的数量  
int m; //边的数量  
void Init()  
{  
    memset(pre,-1,sizeof(pre));  
    int Index = 1;  
    int i,x,y,w;  
    for(i=0;i<m;i++)  
    {  
        scanf("%d%d%d",&x,&y,&w);  
          
        edge[Index].v = y;  
        edge[Index].w = w;  
        edge[Index].next = pre[x];  //保存x起点的上一条边在edge数组中的位置  
        pre[x] = Index++;  //位置更新  
    }  
}  
void print()  
{  
    for(int i=1;i<=n;i++)  
    {  
        printf("%d/n",i);  
        for(int j=pre[i];j!=-1;j=edge[j].next)  
        {  
            printf(" -> %d value is %d/n",edge[j].v,edge[j].w);  
        }  
        //printf("/n");  
    }  
}  
int main()  
{  
    while(scanf("%d%d",&n,&m)!=EOF && (n!=0 || m!=0))  
    {  
        Init();  
        print();  
    }  
    return 0;  
}  

猜你喜欢

转载自blog.csdn.net/cgmm2333/article/details/82632924