---
id: 766
lang: en
translation_of: index.md
source_sha256: 0f344105fc940bfa2ee6426daa102da5fed28782fadd87f97ef23a16b2b880cd
title: "P3914: Counting Colorings — Solution"
description: "My first idea was O(n^3); after a TLE, an array tot[] of totals removes the second dimension of the DP."
tags: ["Dynamic Programming","OI","DP","Counting"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "Problem title 染色计数 rendered as “Counting Colorings”."
---

## Main Idea

This problem is fairly interesting. At first I came up with an $O(n^3)$ complexity, and after typing it up and getting TLE I thought about the prefix-difference approach, but I was <span class="slang" data-zh="太 Naive" data-gloss="tài Naive, “too naive”. An echo of the Chinese internet catchphrase “too young, too simple, sometimes naive”; mocking oneself for being clueless.">too naive</span> and didn't quite trust (?) subtraction under the modulus, so I only got this idea working after reading the solutions.

The DP equation for this problem isn't hard to come up with. It is:

$$
dp[u][i] = \sum_{t \in dst} \sum_{j \in color(t)} dp[t][j], i \neq j
$$

Actually, we can eliminate the second dimension: consider an array of totals $tot[]$, and we get:

$$
dp[u][i] = \sum_{t \in dst} tot[t] - dp[t][i]
$$

And then it's done.

## Code

```cpp
// P3914.cpp
#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 5050, MOD = 1e9 + 7;
int head[MAX_N], current, n, m, tmpx, tmpy, dp[MAX_N][MAX_N], tot[MAX_N];
struct edge
{
    int to, nxt;
} edges[MAX_N << 1];
void addpath(int src, int dst)
{
    edges[current].to = dst, edges[current].nxt = head[src];
    head[src] = current++;
}
void dfs(int u, int fa)
{
    for (int i = head[u]; i != -1; i = edges[i].nxt)
        if (edges[i].to != fa)
            dfs(edges[i].to, u);
    for (int i = 1; i <= m; i++)
    {
        if (!dp[u][i])
            continue;
        for (int e = head[u]; e != -1; e = edges[e].nxt)
        {
            if (edges[e].to == fa)
                continue;
            dp[u][i] = (1LL * dp[u][i] * 1LL * (tot[edges[e].to] - dp[edges[e].to][i])) % MOD;
        }
        while (dp[u][i] < 0)
            dp[u][i] += MOD;
        tot[u] = (1LL * tot[u] + 1LL * dp[u][i]) % MOD;
    }
}
int main()
{
    memset(head, -1, sizeof(head));
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= n; i++)
    {
        scanf("%d", &tmpy);
        for (int j = 1; j <= tmpy; j++)
            scanf("%d", &tmpx), dp[i][tmpx] = 1;
    }
    for (int i = 1; i < n; i++)
        scanf("%d%d", &tmpx, &tmpy), addpath(tmpx, tmpy), addpath(tmpy, tmpx);
    dfs(1, 0);
    printf("%d", tot[1] % MOD);
    return 0;
}
```
