列表

详情


NC15681. ZJH and Monkeys

描述

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 uand monkey v­i.

输出描述

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)

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

C++11(clang++ 3.9) 解法, 执行用时: 284ms, 内存消耗: 11484K, 提交时间: 2020-02-29 13:24:15

#include<stdio.h>
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int n,m;
int t;
vector<int> vec[300005];
ll p1,p2;
void dfs(int u,int pre,int k)
{
	if(k%2) p1++;
	for(int i=0;i<vec[u].size();i++)
	{
		int v=vec[u][i];
		if(v!=pre) dfs(v,u,k+1);
	}
 } 
 int main()
 {
 	cin>>t;
 	while(t--)
 	{
 		p1=0;
 		p2=0;
 		cin>>n;
 		int u,v;
 		for(int i=1;i<n;i++)
 		{
 			scanf("%d%d",&u,&v);
 			vec[u].push_back(v);
 			vec[v].push_back(u);
		 }
		 dfs(1,0,0);
		 p2=n-p1;
		 ll ans=0;
		 if(n&1)
		 ans=p1*p2*p2*2+p1*p1*p2*2;
		 else
		 ans=p1*p1*n+p2*p2*n;
		 cout<<ans<<endl;
		 for(int i=1;i<=n;i++)
		 vec[i].clear();
	 }
	 return 0;
 }

上一题