HDOJ 4705 Y 树形DP
Posted slgkaifa
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDOJ 4705 Y 树形DP相关的知识,希望对你有一定的参考价值。
DP:求出3点构成链的方案数 。然后总方案数减去它
Y
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)Total Submission(s): 1738 Accepted Submission(s): 493
Problem Description
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
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <vector> #pragma comment(linker, "/STACK:16777216") using namespace std; typedef long long int LL; const int maxn=100100; vector<int> g[maxn]; int n; LL ans,doubi[maxn],son[maxn]; void dfs(int u,int fa) { LL ndoubi=0,nson=0; son[u]=1; for(int i=0,sz=g[u].size();i<sz;i++) { int v=g[u][i]; if(v==fa) continue; dfs(v,u); son[u]+=son[v]; doubi[u]+=doubi[v]+son[v]; ans+=son[v]*nson; ans+=son[v]*ndoubi; ans+=doubi[v]*nson; ans+=doubi[v]; nson+=son[v]; ndoubi+=doubi[v]; } } int main() { while(scanf("%d",&n)!=EOF) { ans=0; memset(doubi,0,sizeof(doubi)); memset(son,0,sizeof(son)); for(int i=0;i<=n+10;i++) g[i].clear(); for(int i=0;i<n-1;i++) { int a,b; scanf("%d%d",&a,&b); g[a].push_back(b); g[b].push_back(a); } dfs(1,1); cout<<1LL*n*(n-1)*(n-2)/6-ans<<endl; } return 0; }
以上是关于HDOJ 4705 Y 树形DP的主要内容,如果未能解决你的问题,请参考以下文章
HDOJ 题目1520 Anniversary party(树形dp)