题意:给你n个顶点的一棵树,距离为3的两个点之间连一条新的边(原边留下),问所有点对的距离之和。
题解:考虑两个问题, 第一,如果两个点之间的距离是偶数的话,那么连新边之后的距离就变成了原来就距离/2, 未连接新边之前的距离总和可以巧妙利用贡献算出 siz[u] * (n - siz[u]),所以连新边之后就是siz[u] * (n - siz[u]) / 2, 考虑距离为奇数的距离一定是走过了新边之后再走一条老边,所以答案还需要加上 (深度为奇的点数×深度为偶的点数)/2
#include<iostream>
#include<stdio.h>
#include<cmath>
#include<cstring>
#include<stack>
#include<algorithm>
#include<queue>
#include<vector>
#include<set>
#include<map>
#include<climits>
#define fors(i, a, b) for(int i = (a); i <= (b); ++i)
#define scanf1(a) scanf("%d",&a)
#define scanf2(a,b) scanf("%d%d",&a,&b)
#define scanf3(a,b,c) scanf("%d%d%d",&a,&b,&c)
#define scanf4(a,b,c,d) scanf("%d%d%d%d",&a,&b,&c,&d)
#define ll long long
#define readType int
using namespace std;
const int mx = 2e5 + 10;
const int inf = 0x3f3f3f3f;
inline readType read() {
char c = getchar(); readType x = 0, f = 1;
while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return x * f;
}
int n;
struct my{
int to, nex;
}e[mx << 1];
int head[mx];
ll idx = 1;
ll siz[mx];
ll ans;
ll dep[mx];
void add(int a, int b){
e[idx].to = b;
e[idx].nex = head[a];
head[a] = idx ++;
}
void dfs(int u, int fa){
siz[u] = 1;
dep[u] = dep[fa] + 1;
for(int i = head[u]; ~i; i = e[i].nex){
int v = e[i].to;
if(v == fa) continue;
dfs(v, u);
siz[u] += siz[v];
}
}
int main2(){
cin >> n;
memset(head, -1,sizeof head);
for(int i = 1; i < n; i ++){
int u, v;
cin >> u >> v;
add(u, v);
add(v, u);
}
dfs(1, 0);
ll num = 0;//奇数顶点的数量
for(int i = 1; i <= n; i ++){
if(dep[i] & 1) num ++;
ans += siz[i] * (n - siz[i]);
}
ans += num * (n - num);
cout << ans / 2 << endl;
return 0;
}
int main(){
//ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
int _;//_ = read();
_ = 1;
while(_--)main2();return 0;
}