链式前向星建图

 1 /*
 2 //链式前向星维护的是一个边集数组 
 3 const int N = 1e6+5;//边的数目 
 4 int head[N];//某个点相邻的第一条边的编号 
 5 int cnt;//边的数目 
 6 struct Edge{
 7     int to;//这条边到达的终点 
 8     int dis;//这条边的权值 
 9     int next;//这条边指向的下一条边的编号(可以自己想想,并不是上一条,采用的是类似于前插法) 
10 }edge[N];
11 void addEdge(int u,int v,int w){//u->v 的一个权值为w的边 
12     cnt++;
13     edge[cnt].to = v;
14     edge[cnt].dis = w;
15     edge[cnt].next = head[u];
16     head[u] = cnt; 
17 }
18 //遍历
19 int u = 1;
20 for(int i=head[u]; i; i=edge[i].next){
21     cout << u << "->" << edge[i].to << " " << edge[i].dis << endl; 
22 } 
23 */
24 #include<bits/stdc++.h>
25 using namespace std;
26 const int N = 1e5+5;
27 int head[N],cnt;
28 struct Edge{
29     int to,dis,next;
30 }e[N];
31 void addEdge(int u,int v,int w){
32     cnt++;
33     e[cnt].to = v;
34     e[cnt].dis = w;
35     e[cnt].next = head[u];
36     head[u] = cnt;
37 }
38 int main(){
39     int n,m;
40     cin >> n >> m;
41     for(int i=1; i<=m; i++){
42         int u,v,w;
43         cin >> u >> v >> w;
44         addEdge(u,v,w);
45     }
46     int u = 1;
47     for(int i=head[u];i;i=e[i].next){
48         cout << u << "->" << e[i].to << " " << e[i].dis << endl;
49     }
50     return 0;
51 }
52 /*
53 5 6
54 1 2 3
55 2 3 5
56 3 4 6
57 1 3 8
58 4 1 9
59 1 5 6
60 */

猜你喜欢

转载自www.cnblogs.com/zhangqiling/p/12580423.html