Question: Given a tree, find the total number of all its subtrees.
Idea: Define a dp[], dp[u] refers to the number of subtrees with u as the node.
It can be deduced: for all direct child nodes v of u, dp[u]=dp[u]*(dp[v]+1);
It can be understood that (dp[v]+1) is the total number of subtrees that must contain u nodes by adding a u node to all the subtrees formed by the v node.
#include<bits/stdc++.h> using namespace std; const int maxn = 200000 + 10; const int INF=int(1e9); const int mod=10000007; #define ll long long vector<int>edge[maxn]; bool vis[maxn]; ll dp[maxn]; void init(int n) { for(int i=0; i<=n; i++) edge[i].clear(); memset(vis,0,sizeof(vis)); } void dfs(int u) { vis [u] = true; dp[u]=1; for(int i=0; i<edge[u].size(); i++) { int v=edge[u][i]; if(vis[v]) continue; dfs(v); dp[u]=dp[u]*(dp[v]+1)%mod; } return; } int main() { int n; int u, v; scanf("%d",&n); init(n); for(int i=1; i<=n-1; i++) { scanf("%d %d",&u,&v); edge[u].push_back(v); edge[v].push_back(u); } dfs(1); ll ans=0; for(int i=1; i<=n; i++) ans=(ans+dp[i])%mod; printf("%lld\n",ans); return 0; }