Skip to content

Commit 0cc7843

Browse files
1916
1 parent f5a868e commit 0cc7843

File tree

1 file changed

+56
-0
lines changed
  • solutions/1900-1999/1916.count-ways-to-build-rooms-in-an-ant-colony

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
class Solution
2+
{
3+
public:
4+
int waysToBuildRooms(vector<int> &prevRoom)
5+
{
6+
int n = prevRoom.size();
7+
8+
// Construct tree.
9+
vector<vector<int>> g(n);
10+
for (int i = 1; i < n; ++i)
11+
{
12+
g[prevRoom[i]].push_back(i);
13+
}
14+
15+
// Pre-process fac and inv fac.
16+
vector<ll> fac(n + 1, 1), ifac(n + 1, 1);
17+
for (int i = 2; i <= n; ++i)
18+
{
19+
fac[i] = fac[i - 1] * i % mod;
20+
ifac[i] = qpow(fac[i], mod - 2);
21+
}
22+
23+
return dfs(g, fac, ifac, 0).first;
24+
}
25+
26+
private:
27+
using ll = long long;
28+
static constexpr int mod = 1e9 + 7;
29+
30+
ll qpow(ll x, size_t n)
31+
{
32+
ll ans = 1;
33+
for (auto i = n; i; i /= 2)
34+
{
35+
if (i % 2)
36+
ans = ans * x % mod;
37+
x = x * x % mod;
38+
}
39+
return ans;
40+
}
41+
42+
pair<ll, ll> dfs(const vector<vector<int>> &g, const vector<ll> &fac, const vector<ll> &ifac, int cur)
43+
{
44+
if (g[cur].size() == 0)
45+
return {1, 1};
46+
ll ans = 1, l = 0;
47+
for (int nxt : g[cur])
48+
{
49+
auto [tmp, r] = dfs(g, fac, ifac, nxt);
50+
ll comb = (((fac[l + r] * ifac[l]) % mod) * ifac[r]) % mod;
51+
ans = (ans * tmp % mod) * comb % mod;
52+
l += r;
53+
}
54+
return {ans, l + 1};
55+
}
56+
};

0 commit comments

Comments
 (0)