题目链接:传送门
题意:
对于给定的一颗树,求树上有多少个三元组(A,B,C)使得包括A,B,C的路径不是一条简单路径。
简单路径:在一条路径中,若没有重复相同的顶点,该路径称为简单路径。
分析:从反面考虑这个问题,等于所有的三元组-所有由简单路径组成的链的数目。
代码如下:
#pragma comment(linker, "/STACK:16777216") #include <iostream> #include <cstring> #include <cstdio> #include <algorithm> using namespace std; const int maxn = 1e5+10; typedef long long LL; LL dp[maxn]; int head[maxn],ip; struct node { int to,next; } edge[maxn*2]; void add(int u,int v) { edge[ip].to=v; edge[ip].next=head[u]; head[u]=ip++; } void init() { memset(head,-1,sizeof(head)); ip=0; } LL ans,n; void dfs(int u,int pre) { LL sum=0; dp[u]=1; for(int i=head[u]; i!=-1; i=edge[i].next) { int v = edge[i].to; if(v!=pre) { dfs(v,u); dp[u]+=dp[v]; ans-=sum*dp[v]; sum+=dp[v]; } } ans-=sum*(n-dp[u]); } int main() { while(~scanf("%d",&n)) { init(); for(int i=0; i<n-1; i++) { int u,v; scanf("%d%d",&u,&v); add(u,v); add(v,u); } ans = (n*(n-1)*(n-2)/6); dfs(1,0); printf("%I64d\n",ans); } return 0; } /**** 4 1 2 1 3 1 4 ***/
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2025-01-05 23:18:42