利用C++ STL的vector模拟邻接表的代码

关于vector的介绍请看

           https://www.cnblogs.com/zsq1993/p/5929806.html

           https://zh.cppreference.com/w/cpp/container/vector

下面是利用vector模拟邻接表的演示代码:

 1 #include<iostream>
 2 #include<stdio.h>
 3 #include<vector>
 4 using namespace std;
 5 #define maxN 100
 6 #define maxE 10000
 7 struct EdgeNode
 8 {
 9     int to;
10     int w;
11 };
12 vector<EdgeNode> map[maxN];
13 
14 int main(int argc, char** argv) {
15     int n,m;
16     int i,j,w;
17     EdgeNode e;
18     freopen("data.in","r",stdin);
19     cin>>n>>m;//n个点,m条边
20 
21     for(int k=0;k<m;k++)
22     {
23         cin>>i>>j>>w;
24         e.to=j;
25         e.w=w;
26         map[i].push_back(e);
27     }
28 
29     for(i=1;i<=n;i++)
30     {
31         for(vector<EdgeNode>::iterator k=map[i].begin();k!=map[i].end();k++)
32         {
33             EdgeNode t=*k;
34             cout<<i<<' '<<t.to<<' '<<t.w<<endl;
35         }
36     }
37     return 0;
38 }
View Code

 输入样例:

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 2 4
1 6 9
3 1 22
3 2 19
4 3 17
5 8 29
6 1 12
6 5 9
6 7 4
7 4 25
8 3 11
8 7 7

猜你喜欢

转载自www.cnblogs.com/huashanqingzhu/p/9261086.html