链式前向星

前向星(Forward Star)是一种用于表示稀疏图的数据结构,特别适用于存储有向图和无向图的邻接表。前向星的基本思想是将图的边按照起始节点进行分组,每个节点对应一个链表,链表中存储以该节点为起始节点的所有边的终止节点。
在这里插入图片描述

数组版本

#include <iostream>
#include <vector>
using namespace std;

const int MAXN = 100;  // 最大节点数
const int MAXM = 100;  // 最大边数

int head[MAXN], edge[MAXM], nxt[MAXM], tot;

void init() {
    tot = 0;
    fill(head, head + MAXN, -1);
}

void addEdge(int u, int v) {
    edge[tot] = v;
    nxt[tot] = head[u];
    head[u] = tot++;
}

int main() {
    init();

    addEdge(0, 1);
    addEdge(0, 2);
    addEdge(1, 3);
    addEdge(2, 3);

    for (int u = 0; u < 4; u++) {
        cout << "Node " << u << " :";
        for (int i = head[u]; i != -1; i = nxt[i]) {
            cout << " " << edge[i];
        }
        cout << endl;
    }

    return 0;
}

结构体版本

#include "bits/stdc++.h"

using namespace std;

const int N = 1e5;
const int M = 2e5;

struct edge {
    int w;
    int to;
    int next;
};
int idx = 0,head[N];

edge e[M];

void add(int a, int b, int w) {
    e[idx].w = w;
    e[idx].to = b;
    e[idx].next = head[a];
    head[a] = idx++;
}

int main() {
    idx = 0;
    fill(head, head + N, - 1);

    add(0, 1,  3);
    add(0, 3,  2);
    add(2, 1,  6);
    add(3, 2,  1);
    
    // 遍历u点的边
    int u = 0;
    for (int i = head[u]; ~i; i = e[i].next) {
        cout << e[i].to << ": " << e[i].w << endl;
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值