791D Bear and Tree Jumps

D. 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 ofn vertices, numbered 1 through n.

Limak recently learned how to jump. He can jump from a vertex to any vertex within distance at mostk.

For a pair of vertices (s, t) we definef(s, t) as the minimum number of jumps Limak needs to get froms to t. Your task is to find the sum off(s, t) over all pairs of vertices(s, t) such that s < t.

Input

The first line of the input contains two integersn 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. Thei-th of those lines contains two integers ai and bi (1 ≤ ai, bi ≤ n) — the indices on vertices connected withi-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.

如果小熊每次能跳跃的距离为1,那么问题变为求树上任意两点之间距离之和。
对于每一条边sum1和sum2分别表示边的左右点数,ans=各边的sum1*sum2之和即为答案。
而本题最大跳跃距离为k,答案变为(ans+sum)/k。sum为每一条边需要多走x步才能整除k的x之和。
树上任意两点间距离len=depth[x1]+depth[y1]-2*depth[f],f表示点x1和点y1的最近公共祖先。
计算sum的方法:dp[i][j]表示到i点的距离对k取摸为j的点的总数。
则对于任意两点a和b,dis需要满足(len[a][b]+dis)%k==0。
每当搜索到一个点时,用O(k^2)的方法枚举所有情况。

#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<vector>
#define ll long long
using namespace std;
const int maxm = 200005;
vector<int>v[maxm];
ll dp[maxm][5] = { 0 }, a[maxm] = { 0 }, ans = 0;
int k, n;
void dfs(int x, int pre, int num);
int main()
{
	int  i, j, sum, x, y;
	scanf("%d%d", &n, &k);
	for (i = 1;i < n;i++)
	{
		scanf("%d%d", &x, &y);
		v[x].push_back(y);
		v[y].push_back(x);
	}
	dfs(1, -1, 0);
	printf("%lld\n", ans / k);
	return 0;
}
void dfs(int x, int pre, int num)
{
	dp[x][num%k] = 1;
	a[x] = 1;
	for (int i = 0;i < v[x].size();i++)
	{
		int xx = v[x][i];
		if (xx == pre)
			continue;
		dfs(xx, x, num + 1);
		for (int j = 0;j < k;j++)
		{
			for (int r = 0;r < k;r++)
			{
				int dis = (j + r - num * 2) % k;
				int rev = (k - dis) % k;
				ans += rev*dp[x][j] * dp[xx][r];
			}
		}
		a[x] += a[xx];
		for (int j = 0;j < k;j++)
			dp[x][j] += dp[xx][j];
		ans += (n - a[xx])*a[xx];
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值