A - Distance in Tree
題意:給你一棵樹,讓你記錄樹上兩點距離為k的點對數。
思路:
dp[i][j]代表考慮i這顆子樹,與它距離為j的點數量,dp[i][0]就是1了,然後dfs處理一下就可以,那麼它就是答案的一部分,還有一部分就是把i當做中轉節點,從u開始遞迴,列舉它的每個子樹,ans+=(dp[u][tt]-dp[j][tt-1])*(dp[j][k-tt-1]),最後別忘記除以二,最後有點小疑惑,為什麼這樣就是答案了呢,會不會重複或者漏算呢,首先dp[i][k]加起來肯定是不重複的,然後畫畫圖發現把u當做中轉的也不會有重複。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=50010,M=100010;
int n,k;
int h[N],e[M],ne[M];
int dp[N][510];
ll ans;
int idx;
void add(int a,int b)
{
e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}
void dfs(int u,int fa)
{
dp[u][0]=1;
for(int i=h[u];~i;i=ne[i])
{
int j=e[i];
if(j==fa)
continue;
dfs(j,u);
for(int t=1;t<=k;t++)
dp[u][t]+=dp[j][t-1];
}
ans+=dp[u][k];
ll tmp=0;
for(int i=h[u];~i;i=ne[i])
{
int j=e[i];
if(j==fa)
continue;
for(int t=1;k-t-1>=0;t++)
tmp+=(dp[u][t]-dp[j][t-1])*(dp[j][k-t-1]);
//ans+=tmp/2;
}
ans+=tmp/2;
}
int main()
{
cin>>n>>k;
memset(h,-1,sizeof h);
for(int i=0;i<n-1;i++)
{
int a,b;
cin>>a>>b;
add(a,b);
add(b,a);
}
dfs(1,-1);
// for(int i=1;i<=n;i++)
// {
// for(int j=0;j<=k;j++)
// cout<<dp[i][j]<<' ';
// cout<<endl;
// }
cout<<ans<<endl;
return 0;
}
相關文章
- ABC359 G - Sum of Tree Distance
- abc359_G Sum of Tree Distance 題解
- P9058 [Ynoi2004] rpmtdq 與 P9678 [ICPC2022 Jinan R] Tree DistanceNaN
- Matrix Distance
- [Leetcode] Edit DistanceLeetCode
- 7.47 CLUSTER_DISTANCE
- POI2012ODL-Distance
- distance(Floyd求最短路)
- 477-Total Hamming Distance
- LeetCode 461. Hamming DistanceLeetCode
- 錯誤 1 error LNK2019: 無法解析的外部符號 "public: __thiscall Distance::Distance(int)" (??0Distance@@QAE@H@Z),該符...Error符號
- 漢明距離(Hamming distance)
- [LeetCode] 2739. Total Distance TraveledLeetCode
- 【Lintcode】1623. Minimal Distance In The Array
- [LeetCode] 243. Shortest Word DistanceLeetCode
- LeetCode之Shortest Distance to a Character(Kotlin)LeetCodeKotlin
- [Over-Distance] Ubuntu 24.04 LTS UpdateUbuntu
- 1046 Shortest Distance(簡單模擬)
- [LeetCode] 244. Shortest Word Distance IILeetCode
- [ABC353F] Tile Distance 題解
- [LeetCode] 317. Shortest Distance from All BuildingsLeetCodeUI
- tree
- [LeetCode] 1385. Find the Distance Value Between Two ArraysLeetCode
- Java解決LeetCode72題 Edit DistanceJavaLeetCode
- DSU on Tree
- Rebuild TreeRebuild
- 01 Tree
- Tree Compass
- Decision Tree
- 【MySQL(1)| B-tree和B+tree】MySql
- LeetCode 1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance??LeetCode
- 多路查詢樹:B-tree/b+tree
- LeetCode#110.Balanced Binary Tree(Tree/Height/DFS/Recursion)LeetCode
- segment tree beats
- Circular Spanning Tree
- B-tree
- B+tree
- tree-shaking