给出一颗树,对他进行加边,如果三个顶点u,v,w,u连到v,v连到w,那么u和w之间加一条边。问最后每对点的距离之和。每条边权值为1
代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll,ll>pii;
typedef vector<int>vi;
#define rep(i,a,b) for(int i=(a);i<(b);++i)
#define per(i,a,b) for(int i=(a);i>(b);--i)
#define de(x) cout<<#x<<"="<<x<<endl
#define dd(x) cout<<#x<<"="<<x<<" "
const int N=2e5+5;
ll sz[N];
ll num=0;
vector<int>G[N];
bool vis[N];
void dfs(int u,int deep){
if(deep&1)num++;
sz[u]=1;
rep(i,0,G[u].size()){
int v=G[u][i];
if(!vis[v]){
vis[v]=true;
dfs(v,deep+1);
sz[u]+=sz[v];
}
}
}
int main(){
int n;
cin>>n;
int u,v;
rep(i,1,n){
cin>>u>>v;
G[u].push_back(v);
G[v].push_back(u);
}
memset(vis,false,sizeof(vis));
vis[1]=true;
dfs(1,1);
ll ans=0;
rep(i,1,n+1){
ans+=sz[i]*(n-sz[i]);
}
ans=ans-(ans-num*(n-num))/2;
cout<<ans<<endl;
}