题目:
Y
原题链接:http://acm.hdu.edu.cn/showproblem.php?pid=4705
分析:树形dp的思想,枚举中间点。
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<cmath> 5 #include<algorithm> 6 #include<vector> 7 #include<stack> 8 using namespace std; 9 #define maxn 100005 10 #define LL __int64 11 #pragma comment(linker, "/STACK:16777216") 12 vector<int>e[maxn]; 13 LL ans,sum,n; 14 bool vis[maxn]; 15 int dfs(int s) 16 { 17 vis[s]=true; 18 int son,t=0; 19 for(int i=0;i<e[s].size();i++) 20 { 21 int to=e[s][i]; 22 if(!vis[to]) 23 { 24 son=dfs(to); 25 t+=son; 26 ans+=(LL)(n-t-1)*son; 27 } 28 } 29 return t+1; 30 } 31 int main() 32 { 33 while(scanf("%I64d",&n)!=EOF) 34 { 35 int u,v,m;m=int(n); 36 for(int i=0;i<maxn;i++)e[i].clear(); 37 for(int i=0;i<m-1;i++) 38 { 39 scanf("%d%d",&u,&v); 40 e[u].push_back(v); 41 e[v].push_back(u); 42 } 43 memset(vis,false,sizeof(vis)); 44 ans=0; 45 LL p=dfs(1); 46 sum=n*(n-1)*(n-2)/6; 47 printf("%I64d\n",sum-ans); 48 } 49 return 0; 50 }