QOJ.ac
QOJ
ID | Problem | Submitter | Result | Time | Memory | Language | File size | Submit time | Judge time |
---|---|---|---|---|---|---|---|---|---|
#522556 | #5706. Village | bachbeo2007 | 0 | 0ms | 3768kb | C++23 | 2.2kb | 2024-08-17 01:41:30 | 2024-08-17 01:41:30 |
answer
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define pii pair<int,int>
#define maxn 100005
int n,child[maxn],dep[maxn],ans=0,cnt=0;
vector<int> edge[maxn],ver[maxn],x;
deque<int> dq;
bool cmp(int a,int b){
return (int)ver[a].size()>(int)ver[b].size();
}
void dfs(int u,int par){
ver[cnt].push_back(u);
child[u]=1;dep[u]=dep[par]+1;
ans+=2*dep[u];
for(int v:edge[u]){
if(v==par) continue;
dfs(v,u);child[u]+=child[v];
}
}
int findcen(int u,int par){
for(int v:edge[u]){
if(v==par) continue;
if(child[v]>n/2) return findcen(v,u);
}
return u;
}
signed main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);cout.tie(NULL);
cin >> n;
for(int i=1;i<n;i++){
int u,v;cin >> u >> v;
edge[u].push_back(v);
edge[v].push_back(u);
}
dfs(1,0);
int root=findcen(1,0);
ans=0;dep[root]=0;
for(int v:edge[root]){
cnt++;dfs(v,root);
x.push_back(cnt);
}
cnt++;ver[cnt].push_back(root);
x.push_back(cnt);
sort(x.begin(),x.end(),cmp);
int num=0;
bool ok=false;
for(int v:x){
if(!ok && (num+(int)ver[v].size())>n/2){
int k=min(2*(num+(int)ver[v].size())-n,n-2*num);
if(2*(num+(int)ver[v].size())-n<n-2*num){
for(int i=0;i<(int)ver[v].size()-k;i++) dq.push_back(ver[v][i]);
for(int i=0;i<k;i++){dq.push_back(dq.front());dq.pop_front();}
for(int i=(int)ver[v].size()-k;i<(int)ver[v].size();i++) dq.push_front(ver[v][i]);
}
else{
for(int i=0;i<k;i++){dq.push_back(dq.front());dq.pop_front();}
for(int i=0;i<k;i++) dq.push_front(ver[v][i]);
for(int i=k;i<(int)ver[v].size();i++) dq.push_back(ver[v][i]);
}
ok=true;
}
else{
for(int a:ver[v]) dq.push_back(a);
}
num+=(int)ver[v].size();
}
vector<pii> p;
for(int v:x){
for(int a:ver[v]){
p.push_back({a,dq.back()});
dq.pop_back();
}
}
sort(p.begin(),p.end());
cout << ans << '\n';
for(pii a:p) cout << a.second << ' ';
}
Details
Tip: Click on the bar to expand more detailed information
Subtask #1:
score: 0
Wrong Answer
Test #1:
score: 0
Wrong Answer
time: 0ms
memory: 3768kb
input:
4 1 2 2 3 3 4
output:
8 4 3 2 1
result:
wrong output format Unexpected end of file - int32 expected
Subtask #2:
score: 0
Skipped
Dependency #1:
0%
Subtask #3:
score: 0
Skipped
Dependency #1:
0%