hdu 4705 dfs统计更新节点信息
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4705
#pragma comment(linker, "/STACK:16777216") #include <cstdio> #include <cstring> #include <iostream> #include <cmath> #include <algorithm> #include <queue> #include <vector> using namespace std; const int maxn = 110010; long long dp[maxn]; vector<int> G[maxn]; long long num[maxn]; long long N; long long ans; void dfs(int u,int fa){ for(int i=0;i<G[u].size();i++){ int v = G[u][i]; if(v == fa) continue; dfs(v,u); num[u] += num[v]; } long long numfa = N - num[u]; for(int i=0;i<G[u].size();i++){ int v = G[u][i]; if(v == fa){ long long temp = num[u]-1; dp[u] += numfa * temp; continue; } long long temp = N - num[v] - 1; dp[u] += num[v] * temp; } ans += dp[u]; } int main() { // freopen("E:\\acm\\input.txt","r",stdin); while(cin>>N){ memset(dp,0,sizeof(dp)); for(int i=1;i<=N;i++) num[i] = 1; for(int i=1;i<=N;i++) G[i].clear(); int a,b; for(int i=1;i<=N-1;i++){ scanf("%d%d",&a,&b); G[a].push_back(b); G[b].push_back(a); } ans = 0; dfs(1,-1); long long MAX; MAX = N*(N-1)*(N-2); //N写成int,比赛时wa的太痛苦了,还是队友看出来了。以后要注意了。 cout<<(MAX-ans*3)/6<<endl; } return 0; }