图的存储

以下存取方式均为带权图

一、邻接矩阵

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 int n,m,a[1000][1000],x,y,c;
 5 int main()
 6 {
 7     scanf("%d%d",&n,&m);
 8     memset(a,0,sizeof(a)); //默认没有边
 9     for (int i=1;i<=m;i++)
10     {
11         scanf("%d%d%d",&x,&y,&c);
12         a[x][y]=c;
13      } 
14     for (int i=1;i<=n;i++)
15     {
16         for (int j=1;j<=n;j++) printf("%d ",a[i][j]);
17         printf("\n"); 
18     }
19     return 0;
20  } 

 

二、邻接链表

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 const int maxn=1000;
 5 const int maxm=10000;
 6 struct Edge
 7 {
 8     int x,y,next,c;
 9 }edge[maxm*2];
10 int sumedge,head[maxn],x,y,c,n,m;
11 int insedge(int x,int y,int c)
12 {
13     sumedge++;
14     edge[sumedge].x=x;
15     edge[sumedge].y=y;
16     edge[sumedge].next=head[x];
17     edge[sumedge].c=c;
18     head[x]=sumedge;
19     return 0;
20 }
21 int main()
22 {
23     scanf("%d%d",&n,&m);
24     sumedge=0;
25     memset(head,0,sizeof(head));
26     for (int i=1;i<=m;i++)
27     {
28         scanf("%d%d%d",&x,&y,&c);
29         insedge(x,y,c);
30         insedge(y,x,c); 
31      } 
32     return 0;
33  } 

 

posted @ 2017-01-25 16:21  Mr.9Pounds15Pence  阅读(207)  评论(0编辑  收藏  举报