結果
問題 |
No.1928 Make a Binary Tree
|
ユーザー |
![]() |
提出日時 | 2021-12-15 20:02:18 |
言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 246 ms / 3,000 ms |
コード長 | 1,308 bytes |
コンパイル時間 | 1,104 ms |
コンパイル使用メモリ | 90,984 KB |
最終ジャッジ日時 | 2025-01-26 23:16:54 |
ジャッジサーバーID (参考情報) |
judge2 / judge1 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 57 |
ソースコード
#include <vector> #include <iostream> #include <utility> #include <algorithm> #include <queue> using namespace std; vector<vector<int>> Graph; vector<bool> checked; vector<priority_queue<int>> vec; int dfs(int i,int parent){ checked[i]=true; for(int to:Graph[i]){ if(!checked[to]){ int p=dfs(to,i); vec[i].push(p); } } int max_size=vec[i].size(); int id=i; for(int to:Graph[i]){ if(to!=parent){ if(vec[to].size()>max_size){ id=to; max_size=vec[to].size(); } } } if(id!=i){ while(!vec[i].empty()){ vec[id].push(vec[i].top()); vec[i].pop(); } } for(int to:Graph[i]){ if(id!=to && to!=parent){ while(!vec[to].empty()){ vec[id].push(vec[to].top()); vec[to].pop(); } } } vec[i].swap(vec[id]); int res=1; if(vec[i].size()<=2){ while(!vec[i].empty()){ res+=vec[i].top(); vec[i].pop(); } }else{ for(int j=0;j<2;j++){ res+=vec[i].top(); vec[i].pop(); } } return res; } int main(){ int N; cin>>N; Graph.resize(N); checked.resize(N,false); vec.resize(N); for(int i=0; i<N-1; i++){ int x,y; cin>>x>>y; Graph[x-1].push_back(y-1); Graph[y-1].push_back(x-1); } int ans=dfs(0,-1); cout<<ans<<endl; }