HDU-4705 Y 树形DP

时间:2023-03-09 17:36:55
HDU-4705 Y 树形DP

  题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4705

  题意:给一颗树,从树上任意选择3个点{A,B,C},要求他们不在一条链上,求总共的数目。

  容易想到枚举每个点,然后从每个点的所有分支中选择3个分支,然后从每个分支中选择1个点。假设点u有k个分支,每个分支的节点个数为a1,a2...an,那么方案数就是这个数列中所有3个数的积的和。直接枚举肯定会TLE的。我们可以维护3个前缀和,f1[i]表示前 i 个数选择一个的方案数,f2[i]表示前 i 个数选择两个的方案数,f3[i]表示前 i 个数选择3个的方案数。那么f1[i]就是前缀和,f2[i]=f2[i-1]+f1[i-1]*c[i],f3[i]=f3[i-1]+f2[i-1]*c[i]。然后DFS搜一遍就可以了。。。

 //STATUS:C++_AC_156MS_10508KB
#include <functional>
#include <algorithm>
#include <iostream>
//#include <ext/rope>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <numeric>
#include <cstring>
#include <cassert>
#include <cstdio>
#include <string>
#include <vector>
#include <bitset>
#include <queue>
#include <stack>
#include <cmath>
#include <ctime>
#include <list>
#include <set>
//#include <map>
using namespace std;
#pragma comment(linker,"/STACK:102400000,102400000")
//using namespace __gnu_cxx;
//define
#define pii pair<int,int>
#define mem(a,b) memset(a,b,sizeof(a))
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define PI acos(-1.0)
//typedef
typedef __int64 LL;
typedef unsigned __int64 ULL;
//const
const int N=;
const int INF=0x3f3f3f3f;
const int MOD=,STA=;
const LL LNF=1LL<<;
const double EPS=1e-;
const double OO=1e15;
const int dx[]={-,,,};
const int dy[]={,,,-};
const int day[]={,,,,,,,,,,,,};
//Daily Use ...
inline int sign(double x){return (x>EPS)-(x<-EPS);}
template<class T> T gcd(T a,T b){return b?gcd(b,a%b):a;}
template<class T> T lcm(T a,T b){return a/gcd(a,b)*b;}
template<class T> inline T lcm(T a,T b,T d){return a/d*b;}
template<class T> inline T Min(T a,T b){return a<b?a:b;}
template<class T> inline T Max(T a,T b){return a>b?a:b;}
template<class T> inline T Min(T a,T b,T c){return min(min(a, b),c);}
template<class T> inline T Max(T a,T b,T c){return max(max(a, b),c);}
template<class T> inline T Min(T a,T b,T c,T d){return min(min(a, b),min(c,d));}
template<class T> inline T Max(T a,T b,T c,T d){return max(max(a, b),max(c,d));}
//End struct Edge{
int u,v;
}e[N<<]; int first[N],next[N<<];
int n,m,mt;
LL d[N],c[N],f1[N],f2[N],f3[N];
LL ans; void adde(int a,int b)
{
e[mt].u=a;e[mt].v=b;
next[mt]=first[a];first[a]=mt++;
e[mt].u=b;e[mt].v=a;
next[mt]=first[b];first[b]=mt++;
} void dfs(int u,int fa)
{
int i,j,v,t,cnt=;
f1[]=;
f2[]=f2[]=;
f3[]=f3[]=f3[]=;
d[u]=;
for(i=first[u];i!=-;i=next[i]){
if((v=e[i].v)==fa)continue;
dfs(v,u);
d[u]+=d[v];
}
for(i=first[u];i!=-;i=next[i]){
if((v=e[i].v)==fa)continue;
c[cnt]=d[v];
f1[cnt]=f1[cnt-]+c[cnt];
f2[cnt]=f2[cnt-]+c[cnt]*f1[cnt-];
cnt++;
}
if(cnt<)return;
if(fa!=-){
c[cnt]=n-d[u];
f1[cnt]=f1[cnt-]+c[cnt];
f2[cnt]=f2[cnt-]+c[cnt]*f1[cnt-];
cnt++;
}
if(cnt<)return;
for(i=;i<cnt;i++){
f3[i]=f3[i-]+c[i]*f2[i-];
}
ans+=f3[cnt-];
} int main() {
// freopen("in.txt", "r", stdin);
int i,j,a,b;
while(~scanf("%d",&n))
{
mem(first,-);mt=;
for(i=;i<n;i++){
scanf("%d%d",&a,&b);
adde(a,b);
} ans=;
dfs(,-); printf("%I64d\n",ans);
}
return ;
}