数据结构-图-存储-邻接矩阵-邻接表

数据结构-图-存储

邻接矩阵

存储如下图1,图2

图1

对应邻接矩阵

图2

cpp 复制代码
#include<bits/stdc++.h>
#define MAXN 1005
using namespace std;
int n;
int v[MAXN][MAXN]; 
int main(){
    cin>>n;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            cin>>v[i][j];
        }
    }
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            if(v[i][j]>0){
                cout<<"edge from point "<<i<<" to point "<<j
                <<" with length "<<v[i][j]<<"\n"; 
            }
        } 
    }
    return 0;
}

运行效果:

邻接表

存储示例代码:

cpp 复制代码
#include<bits/stdc++.h>
#define MAXN 1005
using namespace std;
struct edge{
    int to,cost;
};
int n,m;
vector<edge> p[MAXN];
int v[MAXN][MAXN];
int main(){
    cin>>n>>m;
    for(int i=1;i<=m;i++){
        int u,v,l;
        cin>>u>>v>>l;
        p[u].push_back((edge){v,l
        });
    }
    for(int i=1;i<=n;i++){
        for(int j=0;j<p[i].size();j++){
            v[i][p[i][j].to]=p[i][j].cost;
        }
    }
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            cout<<v[i][j]<<' ';
        }
        cout<<"\n";
    }
    return 0;
}

运行效果

相关推荐
神明不懂浪漫23 分钟前
【第四章】索引——B+树、回表,加快数据库的查找能力的利器
开发语言·数据结构·数据库·经验分享·笔记·b树
LuminousCPP1 小时前
数据结构 - 排序(二):快速排序从错误初版到优化版|双指针划分 + 三数取中 + 小区间插入优化
c语言·数据结构·笔记·算法·排序算法
hansang_IR1 小时前
【题解】P9753 [CSP-S 2023] 消消乐
数据结构·c++·算法
shehuiyuelaiyuehao2 小时前
算法40,模拟运算,替换所有的问号
数据结构·算法·leetcode
YSL0701242 小时前
OpenCode保姆级安装教程
数据结构
晴天的雨.9923 小时前
[C++算法]快乐数
数据结构·c++·算法
影视飓风TIM3 小时前
C++11 核心新特性完整梳理
数据结构·c++·算法
晴天的雨.9923 小时前
[C++]算法双指针 复写0
数据结构·c++·算法
mmmmath_33 小时前
LeetCode.438.找到字符串中所有字母异位词
数据结构·算法·leetcode
码少女4 小时前
数据结构——堆排序
数据结构