「Daily OI Round 1」Block
在树上考虑 dp。
对于每个节点,dp 数组保存两个信息。设当前位于点
然后是转移。
如果不选择第
- 选择了若干个相同颜色的子节点。对于若干个颜色相同的节点,每个节点都可以选择选择该点的任意一种方案或不选。设当前子树为
i ,则该点的贡献为f_{i,0}+1 。拿个 map 玩一下,将每种颜色的所有贡献相乘,记s_c=\prod_{i\in son(p) \wedge color(i)=c}f_{i,0}+1 。最后,可以选择任意一种颜色,将他们的贡献相加。不过,每种颜色都有全不选的情况,应当减去这一种,即f_{p,1,0}=\sum_{c} s_c-1 。 - 其他情况。所有选择子节点的情况都已经在上一种情况中考虑过了,我们在此考虑所有不选择子节点的情况。如果不选择某个子节点
i 且不选择当前节点p ,则i 的子树中不为i 的任意一点都不可能与p 的其他儿子[^1]相连。而i 的子树中不选i 的方案数正好为f_{i,1} ,因此f_{p,1,1}=\sum_{i\in son_(p)} f_{i,1} 。
最后的答案即
如果选择第
[^1]: 指以该节点为根的子树中与根距离为
// 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;
}