「Daily OI Round 1」Block

· · 题解

在树上考虑 dp。

对于每个节点,dp 数组保存两个信息。设当前位于点 p,f_{p,0} 表示必须选择 p 的方案数,f_{p,1} 表示必须不选当前点且至少选了一点的方案数。

然后是转移。

如果不选择第 p 个点,分两种情况:

最后的答案即 f_{p,1}=f_{p,1,0}+f_{p,1,1}。

如果选择第 p 个点,该点与其所有儿子与孙子[^2]相连。此时,我可以任意选择所有颜色与 p 相同的儿子或孙子。不过,选择儿子 i 的方案数 f_{i,0} 已经包括了所有选择 i 的儿子的可能方案,所以对于某个儿子 i,其贡献应为选了 i 的方案与未选 i 的方案相加。选了 i 时的方案数,当 i 的颜色与 p 相同时为 f_i,否则不可能选择,为 0。未选 i 时,i 的所有颜色与 p 相同的儿子都可以任意选择一种或不选择。因此,考虑子树 i 总方案数为 t_{i}=\left[color(i)=color(p)\right]\times f_{i,0}+\prod_{j\in son(i)\wedge color(j)=color(p)}f_{j,0}。最后,任意两颗子树之间没有相互影响,f_{p,0}=\sum_{i\in son(p)}t_i。

[^1]: 指以该节点为根的子树中与根距离为 1 的节点。 [^2]: 指以该节点为根的子树中与根距离为 2 的节点。

// include https://raw.githubusercontent.com/atcoder/ac-library/master/atcoder/modint
#include <bits/extc++.h>
using namespace std;
namespace pbds = __gnu_pbds;
istream &fin = cin;
ostream &fout = cout;
using ui = unsigned int;
using uli = unsigned long long int;
using li = long long int;
using mi = atcoder::modint1000000007;
struct Node {
  size_t color;
  vector<Node *> nxt;
  pair<mi, mi> dp;
  size_t id;
  pair<mi, mi> f(Node *fa = nullptr) {
    unordered_map<size_t, mi> s;
    dp.first = 1;
    for (Node *son : nxt)
      if (son != fa) {
        son->f(this);
        s.emplace(son->color, 1).first->second *= son->dp.first + 1;
        dp.second += son->dp.second;
        mi r = 1;
        for (Node *son2 : son->nxt)
          if (son2 != this && son2->color == color) r *= (son2->dp.first + 1);
        dp.first *= (son->color == color ? son->dp.first : 0) + r;
      }
    for (auto const &i : s) dp.second += i.second - 1;
    return dp;
  }
};
int main(void) {
  ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
  size_t n;
  fin >> n;
  vector<Node> nodes(n);
  for (size_t i = 0; i < n; ++i)
    fin >> nodes[i].color, --nodes[i].color, nodes[i].id = i;
  for (size_t i = 1; i < n; ++i) {
    size_t x, y;
    fin >> x >> y;
    --x, --y;
    nodes[x].nxt.emplace_back(&nodes[y]);
    nodes[y].nxt.emplace_back(&nodes[x]);
  }
  nodes[0].f();
  mi ans = nodes[0].dp.first + nodes[0].dp.second;
  fout << ans.val();
  return 0;
}