이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include<bits/stdc++.h>
#include<unordered_map>
using namespace std;
typedef long long ll;
const ll inf=(1ll<<60);
const ll mod=1e9+7;
const int MX=6e5+9;
int n,subtree[MX],par[MX],leaf[MX];
vector<int>v[MX],v1[MX];
void dfs_size(int x,int p){
subtree[x]=1;par[x]=p;
for(auto pp:v[x]){
if(pp==p)continue;
dfs_size(pp,x);
subtree[x]+=subtree[pp];
}
}
int centroid(int x){
dfs_size(x,-1);
int S=subtree[x],idx=1;
queue<int>q;
q.push(x);
while(!q.empty()){
int nxt=q.front();q.pop();
int s=subtree[x]-subtree[nxt];
for(auto pp:v[nxt]){
if(pp==par[nxt])continue;
s=max(s,subtree[pp]);
q.push(pp);
}
if(S>s){
S=s;
idx=nxt;
}
}
return idx;
}
int x,y,cen=1,timer;
void dfs(int x,int p){
if(leaf[x]){
v1[timer].push_back(x);
return;
}
for(auto pp:v[x]){
if(pp==p)continue;
dfs(pp,x);
if(x==cen)timer++;
}
}
int leaves;
int cel(int x,int y){
if(x%y==0)return x/y;
return x/y+1;
}
int main(){
scanf("%d",&n);
if(n==1){
puts("0");
return 0;
}
if(n==2){
puts("1");
cout<<1<<" "<<2<<endl;
return 0;
}
for(int i=0;i<n-1;i++){
scanf("%d%d",&x,&y);
v[x].push_back(y);
v[y].push_back(x);
}
for(int i=1;i<=n;i++){
if(v[i].size()==1){
leaf[i]=1;
leaves++;
}
}
int idx=2;
for(int i=1;i<=n;i++)if(!leaf[i])idx=i;
cen=centroid(idx);
dfs(cen,-1);
priority_queue<pair<int,int> >pq;
for(int i=0;i<timer;i++){
pq.push({v1[i].size(),i});
}
printf("%d\n",cel(leaves,2));
while(pq.size()>1){
int com1=pq.top().second,sz1=pq.top().first;pq.pop();
int com2=pq.top().second,sz2=pq.top().first;pq.pop();
if(sz1<=0||sz2<=0)continue;
printf("%d %d\n",v1[com1][sz1-1],v1[com2][sz2-1]);
--sz1;--sz2;
if(sz1>0)pq.push({sz1,com1});
if(sz2>0)pq.push({sz2,com2});
}
if(pq.size()==1){
printf("%d %d\n",v1[pq.top().second][0],cen);
}
}
컴파일 시 표준 에러 (stderr) 메시지
net.cpp: In function 'int main()':
net.cpp:56:19: warning: ignoring return value of 'int scanf(const char*, ...)', declared with attribute warn_unused_result [-Wunused-result]
scanf("%d",&n);
^
net.cpp:67:28: warning: ignoring return value of 'int scanf(const char*, ...)', declared with attribute warn_unused_result [-Wunused-result]
scanf("%d%d",&x,&y);
^
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |