[转] 池子法 邻接表建图

#include<iostream> 
#include<string.h>
#define Maxn 200 
using namespace std; 
struct edge{int from,to,weight,next;}e[Maxn];//存储边信息的结构体  
int head[Maxn];//起点为下标存储(e中边的位置)  
int main()
{ 
    int edges;//边数  
    memset(head,-1,sizeof(head)); 
    //因为刚开始head不指向任何一条边的下标,所以head都为-1  
    cin>>edges;//边数  
    for(int i=0;i<edges;i++) 
    { 
        cin>>e[i].from>>e[i].to>>e[i].weight;//起点 终点 权重  
        e[i].next=head[e[i].from];
        head[e[i].from]=i;//不容易理解的地方
        /*
        利用head数组存储的是最新的(以数组下标为起点的)边的下标 
        并且该条边的next指向的是同样以数组下标为起点的下一条边的下标 
        直到下一条边的next=-1(即将所有以数组下标为起点的边都遍历了一遍) 
        */ 
    } 
    int cur=0;
    for(int u=1;u<10;u++)//输出图
    { 
        cout<<u<<":"<<endl;
        for(int v=head[u];v!=-1;v=e[v].next)//遍历以u为起点的所有边的信息  
        {
            cur++;
            cout<<e[v].from<<" "<<e[v].to<<" "<<e[v].weight<<endl; 
        }    
        if(cur==edges)
            break;
    } 
    return 0; 
} 
/*
5
3 4 6
3 7 8
1 3 6
2 4 7
3 5 1
*/
原文地址:https://www.cnblogs.com/wuwangchuxin0924/p/5784597.html