题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4705
题意: 有一颗树, 选出3个点。 不在同一条路径上的集合数。
分析:这题主要能逆向思考下,用总的方案数减去A,B,C三点在同一路径上的方案数,就简单了。我们可以确定中间点B,在当前以B为根求得的son中任选一个,在剩下的节点n-tmp-1(tmp为已经求得的B的儿子的个数)中任选一个,产生tmp*(n-tmp-1)中组合。


#pragma comment(linker,"/STACK:102400000,102400000") #include <cstdio> #include <cstring> #include <cmath> #include <iostream> #include <algorithm> #include <queue> #include <cstdlib> #include <stack> #include <vector> #include <set> #include <map> #define LL long long #define mod 1000000007 #define inf 0x3f3f3f3f #define N 100010 #define FILL(a,b) (memset(a,b,sizeof(a))) using namespace std; struct edge {int next,v;edge(){}edge(int v,int next):v(v),next(next){} }e[N*2]; int head[N],tot; LL num[N],sum,n; void addedge(int u,int v) {e[tot]=edge(v,head[u]);head[u]=tot++; } void dfs(int u,int fa) {LL tmp=0;for(int i=head[u];~i;i=e[i].next){int v=e[i].v;if(v==fa)continue;dfs(v,u);num[u]+=num[v];tmp+=num[v];sum+=num[v]*(n-tmp-1);} } int main() {int u,v;while(scanf("%I64d",&n)>0){tot=0;sum=0;memset(head,-1,sizeof(head));for(int i=1;i<=n;i++)num[i]=1;for(int i=1;i<n;i++){scanf("%d%d",&u,&v);addedge(u,v);addedge(v,u);}dfs(1,-1);LL total=(n-2)*(n-1)*n/6;printf("%I64d\n",total-sum);} }