Skip to content

Commit

Permalink
2533: reduce time, memory by using BFS
Browse files Browse the repository at this point in the history
  • Loading branch information
yous committed Sep 23, 2021
1 parent b3a60e7 commit 912bca2
Showing 1 changed file with 37 additions and 21 deletions.
58 changes: 37 additions & 21 deletions problem/2533/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,24 +7,37 @@ using namespace std;

int N;
vector<vector<int>> ADJ;
vector<pair<int, int>> depths;
vector<int> leaves;
vector<int> nodes;
vector<bool> leaves;
vector<int> parents;
vector<bool> early;

void dfs(int u, int s, int depth) {
depths.emplace_back(-depth, u);
bool has_child = false;
for (auto v : ADJ[u]) {
if (v == s) {
continue;
void bfs(void) {
queue<pair<int, int>> qu;
parents[0] = -1;
nodes.emplace_back(0);
qu.emplace(0, -1);
int depth = 1;
while (!qu.empty()) {
int sz = qu.size();
while (sz-- > 0) {
auto [u, s] = qu.front();
qu.pop();
bool has_child = false;
for (auto v : ADJ[u]) {
if (v == s) {
continue;
}
has_child = true;
parents[v] = u;
nodes.emplace_back(v);
qu.emplace(v, u);
}
if (!has_child) {
leaves[u] = true;
}
}
has_child = true;
parents[v] = u;
dfs(v, u, depth + 1);
}
if (!has_child) {
leaves.emplace_back(u);
depth++;
}
}

Expand All @@ -33,6 +46,7 @@ int main() {
cin.tie(nullptr);
cin >> N;
ADJ.resize(N);
leaves.resize(N);
parents.resize(N);
early.resize(N);
for (int i = 0; i < N - 1; i++) {
Expand All @@ -41,17 +55,19 @@ int main() {
ADJ[u - 1].emplace_back(v - 1);
ADJ[v - 1].emplace_back(u - 1);
}
parents[0] = -1;
dfs(0, -1, 0);
bfs();
int ans = 0;
for (auto leaf : leaves) {
if (!early[parents[leaf]]) {
early[parents[leaf]] = true;
for (int u = 0; u < N; u++) {
if (!leaves[u]) {
continue;
}
if (!early[parents[u]]) {
early[parents[u]] = true;
ans++;
}
}
sort(depths.begin(), depths.end());
for (auto [depth, u] : depths) {
for (auto it = nodes.rbegin(); it != nodes.rend(); ++it) {
int u = *it;
if (early[u]) {
continue;
}
Expand Down

0 comments on commit 912bca2

Please sign in to comment.