Y
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)Total Submission(s): 1301 Accepted Submission(s): 387
Problem Description
![](https://i-blog.csdnimg.cn/blog_migrate/59578c418bf7f96b2bdb2376722e0609.jpeg)
Sample Input
4 1 2 1 3 1 4
Sample Output
1Hint1. The only set is {2,3,4}. 2. Please use #pragma comment(linker, "/STACK:16777216")
Source
题意:问树上不在同一条路的三个点对有多少对
题解:先用树dp求以每一个点为中间点在同一条路上的点对数,然后用总数减一下(记得用题目给的语句挂栈)
#pragma comment(linker, "/STACK:16777216")
#include<stdio.h>
#define N 100008
struct node{
int data,next;
}e[2*N];
int head[N],tree[N],all;
long long n,res;
void add(int x,int y)
{
e[++all].next=head[x];
e[all].data=y;
head[x]=all;
}
void dfs(int x,int p)
{
int i,temp=0;
for(i=head[x];i!=-1;i=e[i].next)
{
if(e[i].data==p) continue;
dfs(e[i].data,x);
tree[x]+=tree[e[i].data];
}
for(i=head[x];i!=-1;i=e[i].next)
{
if(e[i].data==p) continue;
res+=tree[e[i].data]*temp;
temp+=tree[e[i].data];
}
res+=(n-1-temp)*temp;
tree[x]++;
}
int main()
{
int i,x,y;
//freopen("t.txt","r",stdin);
while(scanf("%I64d",&n)>0)
{
for(i=0;i<=n;i++)
{
tree[i]=0;
head[i]=e[i].next=-1;
}
for(res=all=i=0;i<n-1;i++)
{
scanf("%d%d",&x,&y);
add(x,y),add(y,x);
}
dfs(1,-1);
printf("%I64d\n",(long long)n*(n-1)*(n-2)/6-res);
}
}