解題思路:
一條邊左邊節點個數乘以右邊頂點個數等於這條邊出現的次數
#include<bits/stdc++.h>
using namespace std;
#define ll long long
vector<int> e[100010];
ll n,ans[100010],cnt;
bool vis[100010];
ll dfs(int x)
{
ll t=0;
for(auto c:e[x])
{
if(!vis[c])
{
vis[c]=true;
ll temp=dfs(c)+1;
t+=temp;
ans[++cnt]=temp*(n-temp);
}
}
return t;
}
int main()
{
cin>>n;
for(int i=0;i<n-1;++i)
{
int x,y;
cin>>x>>y;
e[x].push_back(y);
e[y].push_back(x);
}
vis[1]=true;
dfs(1);
sort(ans+1,ans+n);
long long res=0;
for(int i=1,j=n-1;i<n;++i,--j)
{
res+=ans[i]*j;
}
cout<<res<<endl;
return 0;
}
注意開long long,不開long long後面數據會溢出