题意
求一个数上有几种三点的集合,他们两两的最短路能形成一个三角形。
思路
我们枚举两个点,看有多少个第三点满足条件。
当三个点在同一条链上时,他们的最短路始终满足较小两边加起来等于第三边,不满足三角形。
我们枚举的是其中两个点的最近公共祖先,然后在他的两个子树中各选一个作为其中两个点,那么第三点的数量就是除了这两棵子树和这个点以外的所有点。
代码
#include<bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f3f3f3f3f3f
#define int long long
#define endl "\n"
#define debug(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); err(_it, args); cout << "\n";}
void err(istream_iterator<string> it) {}
template<typename T, typename... Args>
void err(istream_iterator<string> it, T a, Args... args) {
cerr << *it << " = " << a << " ";
err(++it, args...);
}
typedef double db;
typedef long long ll;
typedef unsigned long long ull;
int qmi(int a, int k, int p){int res = 1;while (k){if (k & 1) res = (ll)res * a % p;a = (ll)a * a % p;k >>= 1;}return res;}
int qpow(int a,int b){int res = 1;while(b){if(b&1) res *= a;b>>=1;a*=a;}return res;}
int mo(int x,int p){return x = ((x%p)+p)%p;}
int gcd(int a,int b){return b?gcd(b,a%b):a;}
const int maxn = 1e6+7;
const int mod = 1e9+7;
const double eps = 1e-6;
int dx[] = {0,0,1,-1}, dy[] = {1,-1,0,0};
int T = 1,N,M,K,Q;
int e[maxn],w[maxn],ne[maxn],h[maxn],idx;
void add(int a, int b) {
e[idx] = b, ne[idx] = h[a], h[a] = idx ++;
}
void add(int a, int b, int c) {
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++;
}
int siz[maxn];
int ans = 0;
void dfs(int u, int fa) {
// siz[u] = 1;
// int x = 1;
// int f = 0;
for (int i = h[u]; i != -1; i = ne[i]) {
int j = e[i];
if (j == fa) continue;
dfs(j, u);
// x *= siz[j];
ans += siz[j] * siz[u] * (N - siz[u] - siz[j] - 1);
siz[u] += siz[j];
}
siz[u] ++;
// debug(u, ans, siz[u]);
// if (f) ans += x * (N - siz[u]);
}
void solve(){
memset(h,-1,sizeof(int)*(maxn));
cin >> N;
for (int i = 1; i < N; i ++) {
int u, v, w;
cin >> u >> v >> w;
add(u, v);
add(v, u);
}
dfs(1, -1);
cout << ans << endl;
}
signed main()
{
ios::sync_with_stdio(false);cin.tie(0);
// cin >> T;
for (int i = 1; i <= T; i ++) solve();
return (0-0); //<3
}
// a + b, a + c, b + c;
// a - b, a + c, b + c;