链式前向星
#include <bits/stdc++.h> using namespace std; const int N = 1005; const int M = 2005; struct Node { int v, w, nxt; } node[M]; int cnt, head[N]; // head值和node下标均用于存储边序号,head的下标是结点序号 void addedge(int u, int v, int w) { node[cnt].v = v; node[cnt].w = w; node[cnt].nxt = head[u]; // 把u点指向的边的序号赋值给当前边的nxt head[u] = cnt++; // 把这条边的序号赋值给head } int main() { memset(head, -1, sizeof(head)); // 初始化为-1 int n, m; cin >> n >> m; for (int i = 1; i <= m; i++) { int u, v, w; cin >> u >> v >> w; addedge(u, v, w); } for(int i=1;i<=n;i++){ for(int j=head[i];j!=-1;j=node[j].nxt)cout<<node[j].v<<" value:"<<node[j].w<<" "; cout<<endl; } // system("pause"); return 0; }
更普遍的处理:模拟链表和对应的dfs
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int N=1e5; int head[N],e[N],nxt[N],value[N],idx; int n,m; void addedge(int u,int v,int w){ e[idx]=v; value[idx]=w; nxt[idx]=head[u]; head[u]=idx++; } void visit(int u){ cout<<u;//输出访问点的路径 } bool visited[N]; void dfs(int u){//传入的是某个点的序号 visit(u); visited[u]=true; for(int i=head[u];i!=-1;i=nxt[i]){ int j=e[i];//下一个点的序号 if(visited[j]==false){ dfs(j); } } } int main(){ memset(head,-1,sizeof(head)); cin>>n>>m; for(int i=1;i<=m;i++){ int u,v,w; cin>>u>>v>>w; addedge(u,v,w); addedge(v,u,w); } for(int i=1;i<=n;i++){ for(int j=head[i];j!=-1;j=nxt[j]){ cout<<e[j]<<":"<<value[j]<<"->"; } cout<<endl; } dfs(1);//从1节点开始搜 system("pause"); return 0; }
邻接表(链式前向星和更常用的数组模拟)和dfs,bfs搜索图
最新推荐文章于 2025-04-02 17:22:40 发布