HDU 4705 Y (2013多校10,1010题,简单树形DP)
Y
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 60 Accepted Submission(s): 20
Problem Description
Sample Input
4
1 2
1 3
1 4
Sample Output
1
Hint
1. The only set is {2,3,4}.
2. Please use #pragma comment(linker, "/STACK:16777216")
Source
Recommend
zhuyuanchen520
树形DP统计一遍就可以了。
1 /* *********************************************** 2 Author :kuangbin 3 Created Time :2013/8/22 12:27:59 4 File Name :F:\2013ACM练习\2013多校10\1010.cpp 5 ************************************************ */ 6 #pragma comment(linker, "/STACK:1024000000,1024000000") 7 #include <stdio.h> 8 #include <string.h> 9 #include <iostream> 10 #include <algorithm> 11 #include <vector> 12 #include <queue> 13 #include <set> 14 #include <map> 15 #include <string> 16 #include <math.h> 17 #include <stdlib.h> 18 #include <time.h> 19 using namespace std; 20 21 const int MAXN = 100010; 22 struct Edge 23 { 24 int to,next; 25 }edge[MAXN*2]; 26 int head[MAXN],tot; 27 void init() 28 { 29 memset(head,-1,sizeof(head)); 30 tot = 0; 31 } 32 void addedge(int u,int v) 33 { 34 edge[tot].to = v; 35 edge[tot].next = head[u]; 36 head[u] = tot++; 37 } 38 39 40 int num[MAXN]; 41 int n; 42 long long ans; 43 void dfs(int u,int pre) 44 { 45 num[u] = 1; 46 int tmp = 0; 47 for(int i = head[u];i!= -1;i = edge[i].next) 48 { 49 int v = edge[i].to; 50 if(v == pre)continue; 51 dfs(v,u); 52 ans += (long long)tmp*num[v]; 53 num[u] += num[v]; 54 tmp += num[v]; 55 } 56 ans += (long long)tmp*(n-num[u]); 57 } 58 59 60 int main() 61 { 62 //freopen("in.txt","r",stdin); 63 //freopen("out.txt","w",stdout); 64 int u,v; 65 while(scanf("%d",&n) == 1) 66 { 67 init(); 68 for(int i = 1;i < n;i++) 69 { 70 scanf("%d%d",&u,&v); 71 addedge(u,v); 72 addedge(v,u); 73 } 74 ans = 0; 75 dfs(1,-1); 76 long long tot = (long long)n*(n-1)*(n-2)/6; 77 printf("%I64d\n",tot-ans); 78 } 79 return 0; 80 }
人一我百!人十我万!永不放弃~~~怀着自信的心,去追逐梦想