#include <bits/stdc++.h>
#include <stdio.h>
#define N 100005
using namespace std;
struct edge
{
int from;
int to;
edge(int i=0,int j=0)
{
from = i;to = j;
}
};
vector<edge>mp;
int visit[N];
int num[N];
int depth = 1;
int maxdepth = 1;
int cmp(edge l,edge r)
{
return l.from < r.from;
}
void dfs(int from)
{
edge tmp(from,0);
depth++;
maxdepth = max(maxdepth,depth);
auto pos = lower_bound(mp.begin(),mp.end(),tmp,cmp);
for(auto it=pos;it!=mp.end();it++)
{
if(it->from == from && !visit[it->to])
{
//printf("%d to %d\n",it->from,it->to);
visit[it->to] = 1;
num[depth] ++;
dfs(it->to);
}
if(it->from != from)
break;
}
depth--;
}
int main()
{
int n;
int ans = 0;
cin>>n;
for(int i=0;i<n-1;i++)
{
int a,b;
cin>>a>>b;
edge tmp(a,b);
mp.push_back(tmp);
}
sort(mp.begin(),mp.end(),cmp);
visit[1] = 1;
dfs(1);
for(int i=2;num[i];i++)
{
ans += (num[i] - 1) * 2 + 1;
//printf("num[%d] = %d\n",i,num[i]);
}
cout<<ans<<endl;
return 0;
}
第一题,dfs记录树的深度的数量存在num数组
ans += (num[i] - 1) * 2 + 1;