链式前向星

之前一直习惯用邻接表存图,链式前向星几乎没有写过,但是最近看一些图论的复杂问题时,只找到了用链式前向星写的博客,所以就准备整理个按我的码风写的链式前向星的模版。

大多数博客讲解链式前向星时都读着生硬(可能是受限于文字载体),我有幸看到AgOH的讲解视频,觉得该视频对链式前向星的讲解足够明晰。视频中将链式前向星与邻接表中要素建立起联系,想了解链式前向星原理可移步上视频。看完后我用自己的码风实现如下:

//
// Created by Visors on 2020/9/22.
//
// 题目名:【模板】链式前向星
// 题目来源:luogu
// 题目链接:https://www.luogu.com.cn/problem/U81206
// 算法:Front_Star.cpp
// 用途:TODO
// 时间复杂度:O(TODO)
//

#include <bits/stdc++.h>

using namespace std;

int n, m, flag;

struct Edge {
    int to, w, next;

    Edge() = default;

    Edge(int to, int w, int next) : to(to), w(w), next(next) {}
};

vector<Edge> edges;
vector<int> heads;

inline void addEdge(int u, int v, int w) {
    edges.emplace_back(v, w, heads[u]);
    heads[u] = edges.size() - 1;
//    edges.emplace_back(u, w, heads[v]);
//    heads[v] = edges.size() - 1;
}

int main() {
//    ios_base::sync_with_stdio(false);
//    cin.tie(nullptr), cout.tie(nullptr);
    scanf("%d%d%d", &n, &m, &flag);
    edges.resize(m);
    heads.resize(n + 1, -1);
    if (flag) {
        for (int i = 1, x, y, z; i <= m; i++) {
            scanf("%d%d%d", &x, &y, &z);
            addEdge(x, y, z);
        }
    } else {
        for (int i = 1, x, y, z; i <= m; i++) {
            scanf("%d%d%d", &x, &y, &z);
            addEdge(x, y, z);
            addEdge(y, x, z);
        }
    }
    for (int i = 1; i <= n; i++) {
        if (!~heads[i]) puts("");
        else
            for (int j = heads[i]; ~j; j = edges[j].next)
                printf("%d %d %d\n", i, edges[j].to, edges[j].w);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值