結果
| 問題 |
No.1752 Up-Down Tree
|
| コンテスト | |
| ユーザー |
Nachia
|
| 提出日時 | 2021-11-19 23:49:57 |
| 言語 | C++17(gcc12) (gcc 12.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 85 ms / 2,000 ms |
| コード長 | 2,901 bytes |
| コンパイル時間 | 3,365 ms |
| コンパイル使用メモリ | 124,564 KB |
| 最終ジャッジ日時 | 2025-01-25 21:01:26 |
|
ジャッジサーバーID (参考情報) |
judge2 / judge3 |
| 純コード判定しない問題か言語 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 2 |
| other | AC * 20 |
ソースコード
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <atcoder/modint>
using namespace std;
using i32 = int32_t;
using u32 = uint32_t;
using i64 = int64_t;
using u64 = uint64_t;
#define rep(i,n) for(int i=0; i<(n); i++)
using m32 = atcoder::static_modint<1'000'000'007>;
struct leftist_heap{
using Elem = int;
struct Node{
Node* l;
Node* r;
int height;
Elem key;
};
Node* root;
int m_size;
leftist_heap(){
root = nullptr;
m_size = 0;
}
static Node* meld_node_norecursive(Node* root, Node* anotherroot){
if(anotherroot == nullptr){
return root;
}
if(root == nullptr){
root = anotherroot;
return root;
}
vector<Node*> st;
st.reserve(root->height + anotherroot->height);
Node** p1 = &root;
Node** p2 = &anotherroot;
while(true){
if(*p1 == nullptr){
*p1 = *p2;
break;
}
if((*p1)->key < (*p2)->key) swap(*p1, *p2);
st.push_back(*p1);
p1 = &(*p1)->r;
}
auto st_ritr = st.rbegin();
while(st_ritr != st.rend()){
Node* c = *st_ritr;
if(c->l == nullptr){
swap(c->l, c->r);
c->height = 1;
}
else if(c->r == nullptr){
c->height = 1;
}
else{
if(c->l->height < c->r->height){
swap(c->l, c->r);
}
c->height = c->r->height + 1;
}
st_ritr++;
}
return root;
}
void push(const Elem& val){
Node* new_node = new Node();
new_node->height = 1;
new_node->l = nullptr;
new_node->r = nullptr;
new_node->key = val;
root = meld_node_norecursive(root, new_node);
m_size += 1;
}
Elem top(){
return root->key;
}
void pop(){
auto old_root = root;
root = meld_node_norecursive(old_root->l, old_root->r);
delete(old_root);
m_size -= 1;
}
int size(){
return m_size;
}
void meld(leftist_heap r){
m_size += r.m_size;
root = meld_node_norecursive(root, r.root);
r.root = nullptr;
}
};
int N;
vector<vector<int>> E;
leftist_heap dfs(int p, int pre=-1){
leftist_heap res;
for(int e : E[p]) if(e != pre){
res.meld(dfs(e,p));
}
if(res.size() == 0){
res.push(1);
return res;
}
if(res.size() == 1){
auto v = res.top(); res.pop();
res.push(v+1);
return res;
}
int ans1 = res.top(); res.pop();
int ans2 = res.top(); res.pop();
if(ans1 % 2 == 0 && ans2 % 2 == 0){ res.push(ans1+ans2); res.push(1); }
else{ res.push(ans1+ans2+1); }
return res;
}
int main(){
cin >> N;
E.resize(N);
rep(i,N-1){
int u,v; cin >> u >> v; u--; v--;
E[u].push_back(v);
E[v].push_back(u);
}
auto ans = dfs(0).top();
cout << ans << endl;
return 0;
}
struct ios_do_not_sync {
ios_do_not_sync() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
}
} ios_do_not_sync_instance;
Nachia