Submission

Status:

(PPPPPPPPPP)(PPPPPPPPPPPP)(PPPPPPP)(PPPP)(PPPPPPP)(PPPPPPP)

Subtask/Task Score:

{4/4}{14/14}{12/12}{7/7}{20/20}{43/43}

Score: 100

User: PakinDioxide

Problemset: อพยพปลอดภัย (Quartet)

Language: cpp

Time: 0.057 second

Submitted On: 2025-09-24 16:57:35

#include <bits/stdc++.h>
#define ll long long

using namespace std;

const int mxN = 2e5+5;
const ll mod = 1e9+7;

int N, n, m, t[mxN];
vector <int> adj[mxN];

ll dp1[mxN], ans = 0;

void dfs1(int u, int p) {
    for (auto v : adj[u]) if (v != p) dfs1(v, u), dp1[u] += dp1[v];
    dp1[u] += !t[u];
}

void dfs2(int u, int p, ll up) {
    for (auto v : adj[u]) if (v != p) dfs2(v, u, up + dp1[u] - dp1[v]);
    if (!t[u]) return;
    vector <ll> V = {up};
    for (auto v : adj[u]) if (v != p) V.emplace_back(dp1[v]);
    // cout << "U " << u << '\n';
    if (V.size() < 4) return;
    // for (auto &e : V) cout << e << ' '; cout << '\n';
    // BRUTEFORCE
    int x = V.size();
    ll dp[5][x+1];
    memset(dp, 0, sizeof(dp));
    for (int i = 0; i <= x; i++) dp[0][i] = 1;
    for (int i = 1; i <= 4; i++) for (int j = i; j <= x; j++) dp[i][j] = (((dp[i-1][j-1] * V[j-1]) % mod) + dp[i][j-1]) % mod;
    ans += dp[4][x], ans %= mod;
}

int main() {
    ios::sync_with_stdio(0), cin.tie(0);
    cin >> n >> m; N = n+m;
    for (int i = n+1; i <= n+m; i++) t[i] = 1;
    for (int i = 0; i < N-1; i++) {
        int u, v; cin >> u >> v;
        adj[u].emplace_back(v);
        adj[v].emplace_back(u);
    }
    dfs1(1, 1);
    dfs2(1, 1, 0);
    cout << ans << '\n';
    // for (int i = 1; i <= n+m; i++) cout << dp1[i] << ' ';
    // cout << '\n';
}