QOJ.ac
QOJ
ID | Problem | Submitter | Result | Time | Memory | Language | File size | Submit time | Judge time |
---|---|---|---|---|---|---|---|---|---|
#405066 | #7936. Eliminate Tree | ucup-team992# | TL | 0ms | 12904kb | C++20 | 1.9kb | 2024-05-05 10:13:33 | 2024-05-05 10:13:33 |
Judging History
answer
#include <bits/stdc++.h>
using namespace std;
#define F first
#define S second
#define ar array
typedef int uci;
#define int long long
#define rep(i, a, b) for(int i = a; i < (b); ++i)
#define all(x) begin(x), end(x)
#define sz(x) (int)(x).size()
#define ll long long
typedef pair<int, int> pii;
typedef vector<int> vi;
const int MAXN = 2e5+1;
set<int> adj[MAXN];
bool removed[MAXN];
void solve(){
int n; cin >> n;
set<int> leaves;
for (int i = 0; i < n-1; i++) {
int u, v; cin >> u >> v;
adj[u].insert(v);
adj[v].insert(u);
}
stack<pair<int, int>> rem;
auto add = [&](int i) {
if (size(adj[i]) == 1) {
leaves.insert(i);
if (size(adj[*adj[i].begin()]) <= 2) {
rem.push({*adj[i].begin(), i});
}
}
};
for (int i = 1; i <= n; i++) {
add(i);
}
int ans = 0;
int num_removed = 0;
while (num_removed != n) {
if (not empty(rem)) {
auto [a, b] = rem.top(); rem.pop();
if (removed[a]) continue;
ans++;
if (b) {
leaves.erase(b);
removed[b] = true;
num_removed++;
}
removed[a] = true;
num_removed++;
for (auto i: adj[a]) {
if (i != b) {
adj[i].erase(a);
if (size(adj[i]) == 1) {
add(i);
}
else if (size(adj[i]) == 2) {
for (auto j: adj[i]) {
add(j);
}
}
}
}
}
else {
ans++;
rem.push({*leaves.begin(), 0});
}
}
cout << ans << '\n';
}
uci main(){
ios_base::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
solve();
}
Details
Tip: Click on the bar to expand more detailed information
Test #1:
score: 100
Accepted
time: 0ms
memory: 12880kb
input:
5 1 2 2 3 3 4 3 5
output:
4
result:
ok 1 number(s): "4"
Test #2:
score: 0
Accepted
time: 0ms
memory: 12904kb
input:
4 1 2 2 3 3 4
output:
2
result:
ok 1 number(s): "2"
Test #3:
score: -100
Time Limit Exceeded
input:
196666 32025 108673 181779 17115 162570 134230 93003 39673 89144 1269 185919 154408 34896 65369 35860 44720 55698 1390 45520 189805 147867 124511 135459 132555 87303 18031 176314 59695 33352 130640 87272 39716 35749 108807 143493 94486 126512 116598 40212 70895 132216 80855 22241 188737 150354 17346...