Solution [AGC047D] Twin Binary Trees
JWRuixi
·
·
题解
根本不会 FFT……
给定两棵完全相同的 n 层完全二叉树,其中第 i 层编号依次为 2^{i-1},2^{i-1}+1,\dots, 2^i-1。
给定一个 1 到 2^{n-1} 的排列 p,将第一棵树的第 i 个叶子节点连向第二棵树的第 p_i 个叶子节点。
求此图中合法的环的权值和。
称一个环合法当且仅当它恰好经过 2 条非树边,定义一个环的权值为环上点的编号乘积。
答案对 10^9 + 7 取模。
- 分析
考虑对于一个合法的环,因为其恰好经过两条非树边,所以考虑如果从 $u$ 的左子树中的一个叶子节点出发,一定会从其右子树中一个叶子节点返回。
所以可以将整个过程分为两个部分,枚举 $u$:
1. 从 $u$ 左子树出发,统计对于第二棵树上以每个点 $u^\prime$ 为结尾路径的权值,记作 $f_{u^\prime}$;
2. 从 $u$ 右子树出发,统计以每个点 $u^\prime$ 结尾的环的贡献和,具体实现细节可以对于 $u^\prime$,$ans \leftarrow f_{u^\prime}\times now \times fa_u$,就不会算重了!
时间复杂度 $O(n^22^n)$。
- code
```cpp
#include <bits/stdc++.h>
#define LL long long
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2")
using namespace std;
namespace IO{
char ibuf[(1 << 20) + 1], *iS, *iT;
#if ONLINE_JUDGE
#define gh() (iS == iT ? iT = (iS = ibuf) + fread(ibuf, 1, (1 << 20) + 1, stdin), (iS == iT ? EOF : *iS++) : *iS++)
#else
#define gh() getchar()
#endif
#define reg register
inline long long read () {
reg char ch = gh();
reg long long x = 0;
reg char t = 0;
while (ch < '0' || ch > '9') t |= ch == '-', ch = gh();
while (ch >= '0' && ch <= '9') x = (x << 1) + (x << 3) + (ch ^ 48), ch = gh();
return t ? -x : x;
}
inline void write(long long x) {
if (x < 0) {
x = ~(x - 1);
putchar('-');
}
if (x > 9)
write(x / 10);
putchar(x % 10 + '0');
}
}
using IO::read;
using IO::write;
const int maxn(20), maxm(1 << 19), mod(1e9 + 7);
int n, p[maxm], f[maxm], ans;
#define ls(p) (p << 1)
#define rs(p) (p << 1 | 1)
void dfs1 (int u, int now, int opt) {
if (u == 1) return;
now = (LL)now * u % mod;
if (!opt)
f[u] = (LL)(f[u] + now) % mod;
else
ans = (ans + (LL)f[u ^ 1] * now % mod * (u >> 1) % mod) % mod;
dfs1(u >> 1, now, opt);
}
void dfs2 (int u, int now, int opt) {
now = (LL)now * u % mod;
if (u >= (1 << (n - 1))) {
dfs1(p[u], now, opt);
return;
}
dfs2(ls(u), now, opt);
dfs2(rs(u), now, opt);
}
void clr (int u) {
if (!f[u] || u == 1) return;
f[u] = 0;
clr(u >> 1);
}
void clear (int u) {
if (u >= (1 << (n - 1))) {
clr(p[u]);
return;
}
clear(ls(u));
clear(rs(u));
}
int main () {
n = read();
for (int i = 0; i < (1 << (n - 1)); i++) p[i + (1 << (n - 1))] = (1 << (n - 1)) + read() - 1;
for (int i = 1; i < (1 << (n - 1)); i++) {
dfs2(ls(i), i, 0);
dfs2(rs(i), 1, 1);//初值设为 1,避免算重 i。
clear(i);
}
write(ans);
}
```