Codeforces Round #277 (Div. 2) D 计数问题,划分等价类

Codeforces Round #277 (Div. 2) D:Valid Sets

题目大意:

给定n个节点的树,每个节点有一个val值。给一个整数d,问满足的子树的个数,结果mod上1e9+7。

其中d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000),(1 ≤ val ≤ 2000)。


官方题解:

  • Firstly, we solve the case d =  + ∞. In this case, we can forget all ai since they doesn't play a role anymore. Consider the tree is rooted at node 1. Let Fi be the number of valid sets contain node i and several other nodes in subtree of i ("several" here means 0 or more). We can easily calculate Fi through Fj where j is directed child node of i. Complexity: O(n).

  • General case: d ≥ 0. For each node i, we count the number of valid sets contain node i and some other node j such that ai ≤ aj ≤ ai + d (that means, node i have the smallest value a in the set). How? Start DFS from node i, visit only nodes j such that ai ≤ aj ≤ ai + d. Then all nodes have visited form another tree. Just apply case d =  + ∞ for this new tree. We have to count n times, each time take O(n), so the overall complexity is O(n2). (Be craeful with duplicate counting)

我的分析、理解:

1.上面的题解先从没有d的限制的问题考虑,然后在加入d的限制的考虑。放松限制,收缩限制这个方法便于题目的思考。这个方法第一次在 动态规划经典教程中读过。

2.这样的计数问题,可以用一种合理划分方法,将所求的问题划分成许多个不相交且并为全集的同类型的子问题。即用一种合理的方法划分等价类

题目求有多少个满足条件的子树。树选择的根节点不同,树的形状也不相同,容易出错。可以先确定原树的结构,那么其每一棵子树的根节点定的,择结构是定的。则可以将所有的子树以根节点做为划分方法,此时统计每个根节点的子树,再累加即可,没有重复和遗漏。


题解:

typedef long long LL;
const int INF = 1000000007;
const int MOD = 1000000007;
const double eps = 1e-10;
const int maxn = 2010;

int  n, d;
vector<int>vt[maxn];
int a[maxn];
int ans;
int dfs(int u, int fa, int top)
{
    int now = 1;
    REP(r, vt[u].size())
    {
        int v = vt[u][r];
        if (v != fa && make_pair(a[v], v) > make_pair(a[top], top) && a[top] + d >= a[v])
        now = 1LL * now * (dfs(v, u, top) + 1) % MOD;
    }
    return now;
}
int main ()
{
    while (cin >> d >> n)
    {
        ans = 0;
        REP(i, n + 1) vt[i].clear();
        FE(i, 1, n) RI(a[i]);
        REP(i, n - 1)
        {
            int x, y; RII(x, y);
            vt[x].push_back(y);
            vt[y].push_back(x);
        }
        for (int i = n; i >= 1; i--)
        {
            ans = (ans + dfs(i, -1, i)) % MOD;
        }
        cout << ans << endl;
    }
    return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值