链接:
https://www.nowcoder.com/acm/contest/106/A
来源:牛客网
来源:牛客网
题目描述
It’s universally acknowledged that there’re innumerable trees in the campus of HUST.
One day, zjh is wandering in the campus,and he finds a tree with n monkeys
on it, and he labels the monkeys from 1 to n. A triple of monkeys (a,b,c) is called happy if and only if the absolute value of the difference of the distance from c to a the distance from c to b holds the same
parity(奇偶性) as n. Now zjh wants to know how many triples of monkeys are happy.
输入描述:
There are multiple test cases.
The first line of input contains an integer T, indicating the number of test cases.
For each test case:
The first line contains an integer n
In the next n-1 lines, each line contains two integers ui and vi, denoting an edge between monkey ui and monkey vi.
输出描述:
For each test case, output an integer S, denoting the number of triple of monkeys that are happy.
示例1
输入
1 3 1 2 2 3
输出
12
说明
The 12 triples are: (1,2,1) (1,2,2) (1,2,3) (2,1,1) (2,1,2) (2,1,3) (2,3,1) (2,3,2) (2,3,3) (3,2,1) (3,2,2) (3,2,3)
#include<stdio.h> #include<string.h> #include<vector> #include<iostream> #include<algorithm> #define N 100005 using namespace std; typedef long long ll; int dis[N]; ll ans; ll od,ev; int n; vector<int >ve[N]; void dfs(int u,int fa,int dep) { dis[u]=dep; int sz=ve[u].size(); for(int i=0;i<sz;i++){ int v=ve[u][i]; if(v==fa) continue; dfs(v,u,dep+1); } return ; } int main() { int T; int u,v; scanf("%d",&T); while(T--) { scanf("%d",&n); for(int i=1;i<=n;i++) ve[i].clear(); memset(dis,0,sizeof(dis)); for(int i=1;i<n;i++){ scanf("%d %d",&u,&v); ve[u].push_back(v); ve[v].push_back(u); } dfs(1,1,0); od=ev=0; /* for(int i=1;i<=n;i++){ printf("%d ",dis[i]); } printf("\n"); */ for(int i=1;i<=n;i++){ if(dis[i]%2==1) od++; else ev++; } ans=0; if(n%2==1){ ans=od*ev; ans*=2*n; } else{ ans+=od*od; ans+=ev*ev; ans*=n; } printf("%lld\n",ans); } return 0; }