链表实现:
struct node
{
int v; //边的结束顶点
int w; //边的长度
node* next; //指向以同一起点的下一条边的指针
}*first[N]; //first[u]指向以u为起始点的第一条边
void init()
{
memset(first,NULL,sizeof(first));
}
void add(int u, int v, int w)//添加边
{
node* p =new node;
p->v = v;
p->w = w;
p->next = fisrt;
first[u] = p;
}
//使用的时候,找u的邻接点
for(node* p = first[u]; p != NULL; p = p->next)
{
//在这里作相应的处理
}
数组模拟:
struct node
{
int u, v, w;
int next;
}graph[1000];
int head[1000], t;
void init()
{
t = 1;
memset(head, 0, sizeof(memset));
}
void add(int u, int v, int w)
{
graph[t].u = u;
graph[t].v = v;
graph[t].w = w;
graph[t].next = head[u];
head[u] = t;
t++;
}
for(i = head[u]; i; i = graph[i].next)
{
...
}
数组实现的一个应用:http://poj.org/problem?id=3321
解题报告:http://acm.sdut.edu.cn/bbs/read.php?tid=3170&page=1#4303