vector 邻接表的邻居顺序
同样的边,换成 vector<vector<int>>,把阿岚的邻居依次打印出来(用 / 隔开):
#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;
}
vector<vector<int>> build_adj() {
vector<vector<int>> adj(NAMES.size());
for (auto [a, b] : EDGES) {
adj[a].push_back(b);
adj[b].push_back(a);
}
return adj;
}
int main() {
auto adj = build_adj();
string s;
for (int nb : adj[0]) s += (s.empty() ? "" : "/") + NAMES[nb];
cout << s << endl;
}
(本题用 g++ -std=c++17 -O0 编译。)
全部评论