题解 第一题
整题只靠一个结论:轻链一定比重链先访问
然而我没想到
暴力都不知道怎么打
Code:
#include <bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f3f
#define N 100010
#define ll long long
#define fir first
#define sec second
#define make make_pair
#define pb push_back
//#define int long long
char buf[1<<21], *p1=buf, *p2=buf;
#define getchar() (p1==p2&&(p2=(p1=buf)+fread(buf, 1, 1<<21, stdin)), p1==p2?EOF:*p1++)
inline int read() {
int ans=0, f=1; char c=getchar();
while (!isdigit(c)) {if (c=='-') f=-f; c=getchar();}
while (isdigit(c)) {ans=(ans<<3)+(ans<<1)+(c^48); c=getchar();}
return ans*f;
}
int n;
int head[N], size, dep[N], mdep[N], siz[N], ans, dis;
vector< pair<int, int> > order[N];
struct edge{int to, next;}e[N<<1];
inline void add(int s, int t) {e[++size].to=t; e[size].next=head[s]; head[s]=size;}
void dfs1(int u, int fa) {
siz[u]=1;
for (int i=head[u],v; ~i; i=e[i].next) {
v = e[i].to;
if (v==fa) continue;
mdep[v]=dep[v]=dep[u]+1;
dfs1(v, u);
mdep[u]=max(mdep[u], mdep[v]);
siz[u]+=siz[v];
order[u].pb(make(mdep[v], v));
}
sort(order[u].begin(), order[u].end());
//for (auto it:order[u]) cout<<"it: "<<it.fir<<' '<<it.sec<<endl;
}
void dfs2(int u, int fa) {
//cout<<"dfs2 "<<u<<' '<<fa<<' '<<dis<<endl;
if (dis<dep[u]-1) ans+=dis;
else ans+=dep[u]-1;
//cout<<"ans: "<<ans<<endl;
dis=0;
for (auto v:order[u]) {
if (v.sec==fa) continue;
++dis;
dfs2(v.sec, u);
}
++dis;
}
signed main()
{
memset(head, -1, sizeof(head));
n=read();
for (int i=1,u,v; i<n; ++i) {
u=read(); v=read();
add(u, v); add(v, u);
}
dep[1]=1; dfs1(1, 0); dfs2(1, 0);
printf("%d\n", ans);
return 0;
}