传送门http://oj.daimayuan.top/course/10/problem/505
可以注意到如果三个点在同一条链上无论如何都不可能构成三角形,如下
所以只要不是在一条链上的都可以构成三角形,这题就转化成了求树上不在同一条链上的三个点的总方案数,过程如下
具体看代码注释
#include<iostream>
#include<stdio.h>
#include<cmath>
#include<cstring>
#include<stack>
#include<algorithm>
#include<queue>
#include<vector>
#include<set>
#include<map>
#include<climits>
//#include<bits/stdc++.h>
#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 int long long
using namespace std;
const int mx = 1e5 + 10;
const int inf = 0x3f3f3f3f;
inline int read() {
char c = getchar(); int 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;
}
vector<int> g[mx << 1];//保存图
int ans;
int n;
int siz[mx];//该节点子树大小
void dfs(int u, int f){
for(int v : g[u]){
if(v == f) continue;
dfs(v, u);
//先计数当前子树对答案的贡献再把子树加到当前结点,因为这里的siz[u]是
//v结点之前的子树大小
ans += siz[u] * siz[v] * (n - siz[u] - siz[v] - 1);//减一是减去根节点
siz[u] += siz[v];
}
siz[u] ++;//最后再把自身1大小加到u结点,因为计算ans的时候不需要算根节点
}
signed main2(){
cin >> n;
int u, v, w;
for(int i = 1; i < n; i ++){
cin >> u >> v >> w;
g[u].push_back(v);
g[v].push_back(u);
}
dfs(1, 0);//从1开始dfs
printf("%lld\n", ans);
return 0;
}
signed main(){
//ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
int _;//_ = read();
_ = 1;
while(_--)main2();return 0;
}