增加一条无向边
1 void add(int a,int b,int c) //a到b有一条长度为c的边 2 { 3 ++p; 4 e[p].to = b; //这条边到达b点 5 e[p].w = c; //权值是c 6 e[p].next = head[a];//加入这条边 7 head[a] = p; //改变头指针 8 }
遍历
1 void trave() //遍历 2 { 3 for(int i=head[1];i!=0;i=e[i].next) 4 { 5 //... 6 } 7 }
合起来就成这样了
1 #include<iostream> 2 3 using namespace std; 4 5 const int N = 10010 ; 6 7 struct edge{ 8 int to,w,next; 9 }e[N<<1]; //e存储边,to是这条边到达的点,w权值,next下一条边 10 int head[N],p; //头指针 11 12 void add(int a,int b,int c) //a到b有一条长度为c的边 13 { 14 ++p; 15 e[p].to = b; //这条边到达b点 16 e[p].w = c; //权值是c 17 e[p].next = head[a];//加入这条边 18 head[a] = p; //改变头指针 19 } 20 void trave() //遍历 21 { 22 for(int i=head[1];i!=0;i=e[i].next) 23 { 24 //... 25 } 26 } 27 int main() 28 { 29 //... 30 return 0; 31 }