이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include<bits/stdc++.h>
#define pb push_back
#define fi first
#define se second
#define mp make_pair
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef long double ld;
template <typename T> bool chkmin(T &x,T y){return x>y?x=y,1:0;}
template <typename T> bool chkmax(T &x,T y){return x<y?x=y,1:0;}
ll readint(){
ll x=0,f=1; char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
int n,tot;
int mx[500005],cnt[500005];
vector<int> g[500005];
ll res=0,c=1;
vector<pii> f;
void addedge(int x,int y){ g[x].pb(y); g[y].pb(x); }
void dfs(int x,int px,int d){
mx[x]=d;
cnt[x]=1;
for(auto&v:g[x]){
if(v==px) continue;
dfs(v,x,d+1);
if(mx[v]==mx[x]) cnt[x]+=cnt[v];
else if(mx[x]<mx[v]) cnt[x]=cnt[v];
mx[x]=max(mx[x],mx[v]);
}
}
void reroot(int x,int px,int d){
f.clear();
for(auto&v:g[x]){
if(v!=px) mx[v]-=d;
f.pb(mp(mx[v],cnt[v]));
}
sort(f.rbegin(),f.rend());
if((int)f.size()>=3){
ll cur=0,cc=0;
cur=f[0].fi*1ll*(f[1].fi+f[2].fi);
ll s=0;
for(int j=0;j<f.size();j++){
if(f[j].fi==f[2].fi) cc+=s*f[j].se;
if(f[j].fi==f[1].fi) s+=f[j].se;
}
if(res<cur) res=cur,c=cc;
else if(res==cur) c+=cc;
}
int mx_bef=mx[x],cnt_bef=cnt[x];
multiset<int> st;
map<int,int> m;
for(auto&v:g[x]){
st.insert(mx[v]);
m[mx[v]]+=cnt[v];
}
st.insert(0);
m[0]+=1;
for(auto&v:g[x]){
if(v==px) continue;
st.erase(st.find(mx[v]));
m[mx[v]]-=cnt[v];
mx[x]=*prev(st.end())+1;
cnt[x]=m[mx[x]-1];
reroot(v,x,d+1);
st.emplace(mx[v]);
m[mx[v]]+=cnt[v];
}
mx[x]=mx_bef;
cnt[x]=cnt_bef;
}
int main(){
n=readint();
for(int i=1;i<n;i++) addedge(readint(),readint());
dfs(1,1,0);
reroot(1,1,0);
printf("%lld %lld\n",res,c);
return 0;
}
컴파일 시 표준 에러 (stderr) 메시지
road.cpp: In function 'void reroot(int, int, int)':
road.cpp:57:16: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<std::pair<int, int> >::size_type' {aka 'long unsigned int'} [-Wsign-compare]
57 | for(int j=0;j<f.size();j++){
| ~^~~~~~~~~
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |