Sergey Semyonovich is a mayor of a county city N and he used to spend his days and nights in thoughts of further improvements of Nkers' lives. Unfortunately for him, anything and everything has been done already, and there are no more possible improvements he can think of during the day (he now prefers to sleep at night). However, his assistants have found a solution and they now draw an imaginary city on a paper sheet and suggest the mayor can propose its improvements.

Right now he has a map of some imaginary city with $n$ subway stations. Some stations are directly connected with tunnels in such a way that the whole map is a tree (assistants were short on time and enthusiasm). It means that there exists exactly one simple path between each pair of station. We call a path simple if it uses each tunnel no more than once.

One of Sergey Semyonovich's favorite quality objectives is the sum of all pairwise distances between every pair of stations. The distance between two stations is the minimum possible number of tunnels on a path between them.

Sergey Semyonovich decided to add new tunnels to the subway map. In particular, he connected any two stations $u$ and $v$ that were not connected with a direct tunnel but share a common neighbor, i.e. there exists such a station $w$ that the original map has a tunnel between $u$ and $w$ and a tunnel between $w$ and $v$. You are given a task to compute the sum of pairwise distances between all pairs of stations in the new map.


-----Input-----

The first line of the input contains a single integer $n$ ($2 \leq n \leq 200\,000$) — the number of subway stations in the imaginary city drawn by mayor's assistants. Each of the following $n - 1$ lines contains two integers $u_i$ and $v_i$ ($1 \leq u_i, v_i \leq n$, $u_i \ne v_i$), meaning the station with these indices are connected with a direct tunnel.

It is guaranteed that these $n$ stations and $n - 1$ tunnels form a tree.


-----Output-----

Print one integer that is equal to the sum of distances between all pairs of stations after Sergey Semyonovich draws new tunnels between all pairs of stations that share a common neighbor in the original map.


-----Examples-----
Input
4
1 2
1 3
1 4

Output
6

Input
4
1 2
2 3
3 4

Output
7



-----Note-----

In the first sample, in the new map all pairs of stations share a direct connection, so the sum of distances is $6$.

In the second sample, the new map has a direct tunnel between all pairs of stations except for the pair $(1, 4)$. For these two stations the distance is $2$.

Source: codeforces | Difficulty: HARD
Tags: Tree algorithms

Dynamic programming

Graph traversal


Solutions:
import os, sys
from io import BytesIO, IOBase

def main():
	n = int(input())
	path = [[] for _ in range(n)]
	for _ in range(n - 1):
		(a1, b1) = map(lambda xx: int(xx) - 1, input().split())
		path[a1].append(b1)
		path[b1].append(a1)
	(st, poi, visi) = ([0], [0] * n, [1] + [0] * (n - 1))
	(dp, su) = ([[1.0, 0.0] for _ in range(n)], 0.0)
	while len(st):
		(x, y) = (st[-1], path[st[-1]])
		if poi[x] != len(y) and visi[y[poi[x]]]:
			poi[x] += 1
		if poi[x] == len(y):
			su += dp[st.pop()][1]
			if len(st):
				dp[st[-1]][0] += dp[x][1]
				dp[st[-1]][1] += dp[x][0]
		else:
			st.append(y[poi[x]])
			visi[st[-1]] = 1
			poi[x] += 1
	(st, poi, visi, ans, xor) = ([0], [0] * n, [1] + [0] * (n - 1), su, 0)
	dp1 = [su] * n
	while len(st):
		(x, y) = (st[-1], path[st[-1]])
		if poi[x] != len(y) and visi[y[poi[x]]]:
			poi[x] += 1
		if poi[x] == len(y):
			st.pop()
			xor ^= 1
		else:
			i = y[poi[x]]
			dp1[i] = dp1[x] - dp[i][0] + dp[0][xor] - dp[i][1]
			ans += dp1[i]
			st.append(i)
			visi[i] = 1
			poi[x] += 1
			xor ^= 1
	print(int(ans / 2))
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys
import threading
sys.setrecursionlimit(2100000)

def main():

	def counter(graph, vert, memo, pard=None):
		d = 0
		for c in graph[vert]:
			if c != pard:
				if len(graph[c]) == 1:
					memo[c] = 0
				else:
					memo[c] = counter(graph, c, memo, vert)[0]
				d += memo[c] + 1
		return (d, memo)
	n = int(input())
	vizinhos = []
	for _ in range(n):
		vizinhos.append([])
	for _ in range(n - 1):
		(i, j) = map(int, input().split())
		vizinhos[i - 1].append(j - 1)
		vizinhos[j - 1].append(i - 1)
	same = 1
	layer = [0]
	par = [None]
	j = 0
	while layer:
		j += 1
		n_layer = []
		n_pars = []
		for i in range(len(layer)):
			for vert in vizinhos[layer[i]]:
				if vert != par[i]:
					n_layer.append(vert)
					n_pars.append(layer[i])
		layer = n_layer
		par = n_pars
		if j % 2 == 0:
			same += len(layer)
	bipartite = same * (n - same)
	info = counter(vizinhos, 0, [None] * n)[1]
	dist = 0
	for g in info:
		if g != None:
			dist += (g + 1) * (n - g - 1)
	print((dist + bipartite) // 2)
threading.stack_size(140000000)
main_thread = threading.Thread(target=main)
main_thread.start()
main_thread.join()


an = 0
import sys
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc

@bootstrap
def dfs(node, c):
	vis[node] = 1
	x[c] += 1
	global an
	dp[node] = 1
	for i in adj[node]:
		if not vis[i]:
			yield dfs(i, c ^ 1)
			dp[node] += dp[i]
	an += dp[node] * (n - dp[node])
	yield
n = int(input())
adj = [[] for i in range(n)]
dp = [0] * n
for i in range(n - 1):
	(u, v) = map(int, input().split())
	u -= 1
	v -= 1
	adj[u].append(v)
	adj[v].append(u)
vis = [0] * n
x = [0, 0]
dfs(0, 0)
print((an + x[0] * x[1]) // 2)


def main():

	def countchildren(graph, vert, memo, pard=None):
		dumi = 0
		for child in graph[vert]:
			if child != pard:
				if len(graph[child]) == 1:
					memo[child] = 0
				else:
					memo[child] = countchildren(graph, child, memo, vert)[0]
				dumi += memo[child] + 1
		return (dumi, memo)
	n = int(input())
	neigh = []
	for i in range(n):
		neigh.append([])
	for i in range(n - 1):
		(a, b) = map(int, input().split())
		neigh[a - 1].append(b - 1)
		neigh[b - 1].append(a - 1)
	same = 1
	layer = [0]
	pars = [None]
	j = 0
	while layer != []:
		j += 1
		newlayer = []
		newpars = []
		for i in range(len(layer)):
			for vert in neigh[layer[i]]:
				if vert != pars[i]:
					newlayer.append(vert)
					newpars.append(layer[i])
		layer = newlayer
		pars = newpars
		if j % 2 == 0:
			same += len(layer)
	bipartite = same * (n - same)
	info = countchildren(neigh, 0, [None] * n)[1]
	dist = 0
	for guy in info:
		if guy != None:
			dist += (guy + 1) * (n - guy - 1)
	print((dist + bipartite) // 2)
import sys
import threading
sys.setrecursionlimit(2097152)
threading.stack_size(134217728)
main_thread = threading.Thread(target=main)
main_thread.start()
main_thread.join()