对于树上的点,只有深度为奇数的点走到深度为奇数的点和深度为偶数的点走到深度为偶数的点经过的边才会是偶数,dfs一边记录每个点的深度,统计深度为奇数的点的个数n和深度为偶数的点的个数m
ans =
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; typedef long long ll; const int N = 1e5+10; struct Node{ int to,nex; }e[N<<1]; int n,head[N],idx,depth[N]; int mx,cnt[N];//最大深度,深度为i的点有几个 void add_edge(int u,int v){ e[idx].to = v; e[idx].nex = head[u]; head[u] = idx++; } void dfs(int u,int fa){ depth[u] = depth[fa]+1; cnt[depth[u]]++; mx = max(mx,depth[u]); for(int i = head[u];~i;i = e[i].nex){ int v = e[i].to; if(v == fa) continue; dfs(v,u); } } int main(){ scanf("%d",&n); memset(head,-1,sizeof(head)); idx = 0; for(int i = 1;i < n;i++){ int u,v;scanf("%d%d",&u,&v); add_edge(u,v);add_edge(v,u); } dfs(1,0); ll odd = 0,even = 0;//深度为奇数的点个数,深度为偶数的点的个数 for(int i = 1;i <= mx;i++){ if(i&1) odd+=(1ll*cnt[i]); else even+=(1ll*cnt[i]); } ll res = odd*(odd-1)/2+even*(even-1)/2; printf("%lld\n",res); return 0; }