链式前向星存储结构
1 #include <iostream> 2 using namespace std; 3 #define maxN 100 4 #define maxM 10000 5 6 struct EdgeNode 7 { 8 int to; 9 int w; 10 int next; 11 }; 12 EdgeNode Edges[maxM]; 13 int head[maxN]; //需要初始化为0或-1。head[i]存储以点Vi开头的第一条边在边数组Edges[]中的位置。 14 15 int main(int argc, char *argv[]) 16 { 17 int n,m; 18 int i,j,k,w; 19 freopen("data.in","r",stdin); 20 freopen("data.out","w",stdout); 21 memset(head,-1,sizeof(head)); 22 cin>>n>>m;//n个顶点,m条边 23 for(k=0;k<m;k++) 24 { 25 cin>>i>>j>>w; 26 Edges[k].to=j; 27 Edges[k].w=w; 28 Edges[k].next=head[i]; 29 head[i]=k; 30 } 31 //遍历整个图的边 32 for(i=1;i<=n;i++)//这里顶点编号从1开始 33 { 34 for(k=head[i];k!=-1;k=Edges[k].next) 35 { 36 cout<<i<<' '<<Edges[k].to<<" "<<Edges[k].w<<endl; 37 } 38 } 39 /* 40 printf("\n\n"); 41 for(k=1;k<=n;k++) 42 printf("%d\t",k); 43 printf("\n"); 44 for(k=1;k<=n;k++) 45 printf("%d\t",head[k]); 46 printf("\n\n"); 47 48 for(k=0;k<=m;k++) 49 printf("%d\t",k); 50 printf("\n"); 51 for(k=0;k<=m;k++) 52 printf("%d\t",Edges[k].to); 53 printf("\n"); 54 for(k=0;k<=m;k++) 55 printf("%d\t",Edges[k].w); 56 printf("\n"); 57 for(k=0;k<=m;k++) 58 printf("%d\t",Edges[k].next); 59 printf("\n"); 60 */ 61 return 0; 62 }
输入样例数据
8 12
5 8 29
6 1 12
8 3 11
1 2 4
3 1 22
4 3 17
7 4 25
6 5 9
8 7 7
1 6 9
3 2 19
6 7 4
输出结果:
1 6 9 1 2 4 3 2 19 3 1 22 4 3 17 5 8 29 6 7 4 6 5 9 6 1 12 7 4 25 8 7 7 8 3 11 1 2 3 4 5 6 7 8 9 -1 10 5 0 11 6 8 0 1 2 3 4 5 6 7 8 9 10 11 12 8 1 3 2 1 3 4 5 7 6 2 7 0 29 12 11 4 22 17 25 9 7 9 19 4 0 -1 -1 -1 -1 -1 -1 -1 1 2 3 4 7 0