前向星的邻居顺序

👁️ 0 人浏览 💬 0 人评论 ❤️ 添加收藏

用链式前向星存图,从 head[0] 顺着 nxt 把阿岚(0 号)的邻居依次打印出来(用 / 隔开):

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

// 五个人:0 阿岚、1 小满、2 阿泰、3 南风、4 北辰
const vector<string> NAMES = {"阿岚", "小满", "阿泰", "南风", "北辰"};
// 四段关系(无向):阿岚-小满、阿岚-阿泰、小满-阿泰、阿泰-南风
const vector<pair<int, int>> EDGES = {{0, 1}, {0, 2}, {1, 2}, {2, 3}};

int id_of(const string& name) {
    for (int i = 0; i < (int)NAMES.size(); i++) {
        if (NAMES[i] == name) return i;
    }
    return -1;
}

const int MAXN = 5, MAXM = 8;           // 4 条无向边要存 8 条有向边
int head[MAXN], nxt[MAXM], to[MAXM], cnt = 0;

void add_edge(int u, int v) {
    to[cnt] = v;
    nxt[cnt] = head[u];
    head[u] = cnt++;
}

void build_star() {
    for (int i = 0; i < MAXN; i++) head[i] = -1;
    for (auto [a, b] : EDGES) {
        add_edge(a, b);
        add_edge(b, a);
    }
}

int main() {
    build_star();
    string s;
    for (int e = head[0]; e != -1; e = nxt[e]) s += (s.empty() ? "" : "/") + NAMES[to[e]];
    cout << s << endl;
}

(本题用 g++ -std=c++17 -O0 编译。)

提交你的答案
请登录后提交答案。
去登录
代码编辑器
Ctrl + Enter 运行
本次输入:
输出:

                        
👩‍🏫
AI
💬 题目评论

全部评论