三种存图方式

三种存图方式

1.邻接矩阵

2.邻接表

邻接表是一种对于每个顶点,用链表来存储以该点为起点的边的数据结构。

# include <bits/stdc++.h>
using namespace std;

const int MAXN=250;
struct Edge{
   int to,w,next;
}edge[MAXN<<1];
int head[MAXN];
int tot;
void add(int u,int v,int w)
{
   edge[++tot].w=w;
   edge[tot].to=v;
   edge[tot].next=head[u];
   head[u]=tot;
   return ;
}
void init()
{
   tot=1;
   memset(head,-1,sizeof(head));
   memset(edge,0,sizeof(edge));
}


i i^1
# include <bits/stdc++.h>
using namespace std;

const int MAXN=1e4+100;
struct edge{
   int to,w;
   edge(int too,int ww){ to=too; w=ww; }
};
vector<edge> G[MAXN];
void addedge(int u,int v,int w)
{
   G[u].push_back(edge(v,w));
}
int main()
{
   //遍历操作
   for(int i=0;i<G[u].size();i++){
       edge e=G[u][i];
       //操作
  }

   return 0;
}

3.链式前向星

# include <bits/stdc++.h>
using namespace std;

const int MAXN=1e4+100;
struct Edge{
   int next,to,w;
}edge[MAXN];
int tot=0; //边的下标,称为储存位置
int head[MAXN];
void add(int u,int v,int w)
{
   edge[tot].w=w;
   edge[tot].to=v;
   edge[tot].next=head[u]; //和之前的链上
   head[u]=tot++; //更新首位置
}
int main()
{
   memset(head,-1,sizeof(head));
   int n,m; scanf("%d%d",&n,&m);
   for(int i=0;i<m;i++){
       int u,v,w; scanf("%d%d%d",&u,&v,&w);
       add(u,v,w);
  }
   //遍历
   for(int j=1;j<=n;j++){
       for(int i=head[j];~i;i=edge[i].next){
           Edge e=edge[i];
      }
  }

   return 0;
}
/*
9 8
1 2 1
1 3 1
2 4 1
2 5 1
3 6 1
3 7 1
3 8 1
7 9 1
*/



posted @   fengzlj  阅读(190)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示