Codeforces 711C 树DP 解题报告

C. Bear and Tree Jumps

A tree is an undirected connected graph without cycles. The distance between two vertices is the number of edges in a simple path between them.
Limak is a little polar bear. He lives in a tree that consists of n vertices, numbered 1 through n.
Limak recently learned how to jump. He can jump from a vertex to any vertex within distance at most k.
For a pair of vertices (s, t) we define f(s, t) as the minimum number of jumps Limak needs to get from s to t. Your task is to find the sum of f(s, t) over all pairs of vertices (s, t) such that s < t.

Input

The first line of the input contains two integers n and k (2 ≤ n ≤ 200 000, 1 ≤ k ≤ 5) — the number of vertices in the tree and the maximum allowed jump distance respectively.
The next n - 1 lines describe edges in the tree. The i-th of those lines contains two integers ai and bi (1 ≤ ai, bi ≤ n) — the indices on vertices connected with i-th edge.
It’s guaranteed that the given edges form a tree.

Output

Print one integer, denoting the sum of f(s, t) over all pairs of vertices (s, t) such that s < t.

Examples

input
6 2
1 2
1 3
2 4
2 5
4 6
output
20
input
13 3
1 2
3 2
4 2
5 2
3 6
10 6
6 7
6 13
5 8
5 9
9 11
11 12
output
114
input
3 5
2 1
3 1
output
3

【解题报告】

代码如下:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define LL long long
#define N 200010

int cnt=-1,head[N];
struct Edge{int to,nxt;}e[N<<1];
int n,k;
LL dp[N][10],size[N],ans;

void adde(int u,int v)
{
    e[++cnt].to=v;e[cnt].nxt=head[u];head[u]=cnt;
    e[++cnt].to=u;e[cnt].nxt=head[v];head[v]=cnt;
}
void dfs(int u,int fa,int dep)
{
    size[u]=dp[u][dep%k]=1; 
    for(int i=head[u];~i;i=e[i].nxt)
    {
        int v=e[i].to;
        if(v==fa) continue;
        dfs(v,u,dep+1);
        for(int a=0;a<k;a++)  
        for(int b=0;b<k;b++)
        {
            int dis=((a+b)%k-(dep*2)%k+k)%k;  
            ans+=((k-dis)%k)*dp[u][a]*dp[v][b];  
        }
        for(int a=0;a<k;a++) dp[u][a]+=dp[v][a];    
        ans+=size[v]*(n-size[v]);  
        size[u]+=size[v];  
    }
}
int main()
{
    memset(head,-1,sizeof(head));
    scanf("%d%d",&n,&k);
    for(int i=1;i<n;++i)
    {
        int u,v;scanf("%d%d",&u,&v);
        adde(u,v);
    }
    dfs(1,1,0);
    printf("%I64d\n",ans/k);
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值