这两对点连得通吗
问两件事:0 号和 5 号连不连通?1 号和 3 号呢?运行下面这段程序:
本节的图:七个点,边 0-1、0-2、1-3、2-4、3-4、5-6;邻接表 G 里每个点的邻居按编号从小到大排。
#include <algorithm>
#include <iostream>
#include <queue>
#include <string>
#include <utility>
#include <vector>
using namespace std;
vector<vector<int>> G = {{1, 2}, {0, 3}, {0, 4}, {1, 4}, {2, 3}, {6}, {5}};
vector<vector<int>> blocks(const vector<vector<int>>& g) {
vector<bool> seen(g.size(), false);
vector<vector<int>> out;
for (int s = 0; s < (int)g.size(); s++) {
if (seen[s]) continue;
vector<int> blk;
vector<int> st = {s};
seen[s] = true;
while (!st.empty()) {
int u = st.back();
st.pop_back();
blk.push_back(u);
for (int v : g[u]) {
if (!seen[v]) {
seen[v] = true;
st.push_back(v);
}
}
}
sort(blk.begin(), blk.end());
out.push_back(blk);
}
return out;
}
int main() {
vector<vector<int>> b = blocks(G);
auto same = [&](int x, int y) {
for (auto& blk : b) {
bool hx = find(blk.begin(), blk.end(), x) != blk.end();
bool hy = find(blk.begin(), blk.end(), y) != blk.end();
if (hx && hy) return true;
}
return false;
};
cout << boolalpha << same(0, 5) << "/" << same(1, 3) << endl;
}
(本题用 g++ -std=c++17 -O0 编译。)
全部评论