图论-图的存储
发表于:2026-08-18 | 分类: cpp算法

vector邻接表存储图

定义

1
2
3
4
5
struct node{
int v;
int len;
};
vector<node> G[105];

插入

1
2
3
4
5
6
void insertNode(int u,int v,int dis){
node temp;
temp.v=v;
temp.len=dis;
G[u].push_back(temp);
}

查询

1
2
3
4
5
6
7
8
9
vector<int> getDisList(int u,int v){
vector<int> res;
for(int i=0;i<G[u].size();i++){
if(G[u][i].v==v){
res.push_back(G[u][i].len);
}
}
return res;
}

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include<bits/stdc++.h>
using namespace std;

struct node{
int v;
int len;
};
vector<node> G[105];

void insertNode(int u,int v,int dis){
node temp;
temp.v=v;
temp.len=dis;
G[u].push_back(temp);
}

int n,m,q,u,v,d;
bool flag;
int main(){
cin>>n>>m>>q;
for(int i=0;i<m;i++){
cin>>u>>v>>d;
insertNode(u,v,d);
}
for(int i=0;i<q;i++){
flag=false;
cin>>u>>v;
for(int i=0;i<G[u].size();i++){
if(G[u][i].v==v){
if(flag==false){
flag=true;
cout<<"Yes";
}
cout<<" "<<G[u][i].len;
}
}
if(!flag){
cout<<"No";
}
cout<<endl;
}
}

链式前向星

结构定义

1
2
3
4
5
6
struct EDGE{
int next; //下一条边的存储下标(默认0)
int v; //这条边的终点
int len; //权值
};
EDGE edge[500010];

插入

1
2
3
4
5
6
7
void insertNode(int u, int v, int w) {  //起点u, 终点v, 权值w 
//cnt为边的计数,从1开始计
edge[++cnt].next = head[u];
edge[cnt].len = w;
edge[cnt].v = v;
head[u] = cnt; //第一条边为当前边
}

遍历

1
for(int i=head[st]; i!=0; i=edge[i].next)

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <bits/stdc++.h>
using namespace std;

struct node{
int next;
int v;
int len;
};
node G[1005];

int n, m, cnt;
int head[105];

void insertNode(int u, int v, int w) {
G[++cnt].next = head[u];//头插倒序
G[cnt].len = w;
G[cnt].v = v;
head[u] = cnt;
}


int main() {
int u,v,w;
cin>>n>>m;
for(int i=0; i<m; i++) {
cin>>u>>v>>w;
insertNode(u,v,w);
}
for(int i=1;i<=n;i++){
for(int j=head[i];j!=0;j=G[j].next){
cout<<G[j].v<<" ";
}
cout<<endl;
}
return 0;
}
上一篇:
图论-图论相关算法
下一篇:
生日!+博客重大更新