CodeChef:Sereja and Tree 2(树形dp)

Sereja has a rooted tree of N nodes with node 1 being the root node. He wants to find the number of ways of assigning an integer in the range [1, M] to each node, such that value of each node should be a multiple of it's parent node's value (for vertex #1 there is no parent so any number fit condition). As the answer could be large, report it modulo (109 + 7).

Input

The first line of input contains an integer T — the number of test cases. T tests follow.

First line of each test case contains two space-separated integers N and M. Each of the next N-1 lines contains two integers (u, v) — a pair of vertices connected by an edge.

Output

For each test case, output a single integer corresponding to the answer in separate line.

Constraints

  • 1 ≤ T ≤ 10
  • 1 ≤ N ≤ 500
  • 1 ≤ M ≤ 20000
  • 1 ≤ u, v ≤ N
  • It is guaranteed that the given graph is a tree (i.e., there won't be any cycles or self-loops).

Example

Input:
2
3 2
1 2
1 3
1 100

Output:
5
100
题意:Sereja 有一棵 N 个节点的有根树,其中 1 号节点为根。现在他想要给每个节点赋予一个 [1, M]内的整数,而且每个节点的值应当是其父亲的值的倍数(对于根节点,由于其没有父亲,因此可以任意取值)。Sereja 想知道有多少种满足条件的赋值方案。由于答案可能非常大,请输出答案对109 + 7 取模得到的结果。

思路:从叶子算起递归到根节点即可。

# include <bits/stdc++.h>
# define pb push_back
using namespace std;
typedef long long LL;
const LL mod = 1e9+7;
vector<int>g[503];
int n, m;
LL dp[503][20003];
inline void scan(int &ret)
{
	char c; ret=0;
	while((c=getchar())<'0'||c>'9');
	while(c>='0'&&c<='9') ret=ret*10+(c-'0'),c=getchar();
}
inline void out(LL x)
{
   if(x>9) out(x/10);
   putchar(x%10+'0');
}
inline void add(LL &a, LL b)
{
    a += b;
    if(a >= mod) a -= mod;
}
inline void pro(LL &a, LL b)
{
    a *= b;
    if(a >= mod) a%=mod;
}
void dfs(int u, int pre)
{
    for(auto v : g[u])
    {
        if(v == pre) continue;
        dfs(v, u);
        for(int i=1; i<=m; ++i)
        {
            LL sum = 0;
            for(int j=i; j<=m; j+=i)
                add(sum, dp[v][j]);
            pro(dp[u][i], sum);
        }
    }
}
int main()
{
    int T, a, b;
    scan(T);
    while(T--)
    {
        scan(n), scan(m);
        for(int i=1; i<=n; ++i) g[i].clear();
        for(int i=1; i<=n; ++i)
            for(int j=1; j<=m; ++j)
            dp[i][j] = 1LL;
        for(int i=1; i<n; ++i)
        {
            scan(a), scan(b);
            g[a].pb(b);
            g[b].pb(a);
        }
        dfs(1, 0);
        LL ans = 0;
        for(int i=1; i<=m; ++i)
            add(ans, dp[1][i]);
        out(ans);
        putchar('\n');
    }
    return 0;
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值