Test instructions
Give a tree and ask the number of cases where the distance between any two points is K.
Analysis:
It's obviously DP, but how does the state equation go? A tree, it must start from the root node to consider the situation, then each point as a lesson subtree, and then Dp[i][j] represents the number of cases when the distance to K is calculated to I point. Then scan the sub-nodes of the point, recursion, after Ans+=dp[x][j-1]*dp[v][k-j]; Represents the distance to the I node and the distance to the child node ==k-1 all cases, why k-1, not K, because there is an edge length between x and child nodes, and then update the X node.
It is important to add an answer and update the order of x, which cannot be reversed and cannot be mixed. Since the non-update represents a situation where the nodes of V and V have not been met, the update then includes the connection between the V node and the other child nodes into K when computed with the other child nodes. Very ingenious idea.
#include <stdio.h>#include <cstdio>#include <stdlib.h>#include <string.h>#include <algorithm>#include <iostream>#include <set>#include <vector>#include <map>#include <math.h>#define Read Freopen ("Q.in", "R", stdin)#define LL Long Longusing namespace STD;Const intMAXN =50005;Const intN =510;intDP[MAXN][N],VIS[MAXN]; vector<int>VT[MAXN];intN,k,ans;voidDfsintx) {dp[x][0]=1; vis[x]=1;intI,j; for(i=0; I<vt[x].size (); i++) {intV=vt[x][i];if(Vis[v])Continue; DFS (v); for(j=1; j<=k;j++) ans+=dp[x][j-1]*DP[V][K-J]; for(j=1; j<=k;j++) dp[x][j]+=dp[v][j-1]; }}intMain () {//Read; intI,j; while(~scanf("%d%d", &n,&k)) {intU,v; ans=0;memset(Vis,0,sizeof(VIS));memset(DP,0,sizeof(DP)); for(i=0; i<maxn;i++) vt[i].clear (); for(i=0; i<n-1; i++) {scanf("%d%d", &u,&v); Vt[u].push_back (v); Vt[v].push_back (U); } DFS (1);cout<<ans<<endl; }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[Tree DP] VK Cup Round 1 D. Distance in Tree