给定一棵树,求树上不相交的路径对数。
容斥一下:不相交路径对数 = 总路径对数 - 相交路径对数
考虑如何计算相交路径对数:枚举点 i i i作为一条路径的 L C A LCA LCA,则此时的相交方案数为经过 i i i且 L C A LCA LCA不在 i i i的路径数 × $LCA 为 为 为i 的路径数 + 的路径数 + 的路径数+LCA 都在 都在 都在i$的路径对数。
那么直接树上计数然后容斥即可。
Code#include
#pragma gcc optimize(2)
#define int long long
#define endl '\n'
using namespace std;
const int N = 2e5 + 10, MOD = 1e9 + 7;
vector g[N];
int sz[N], ans = 0;
int n = 0;
void dfs(int u, int fa){
int res = 0;
sz[u] = 0;
for(auto v : g[u]){
if(v == fa) continue;
dfs(v, u);
(res += sz[v] * sz[u]) %= MOD;
sz[u] += sz[v];
}
sz[u]++;
int t = (res + sz[u]) % MOD;
(ans += ((n - sz[u]) * sz[u] % MOD * t % MOD)) %= MOD;
(ans += (t * (t + 1) / 2) % MOD) %= MOD;
}
inline void solve(){
cin >> n; ans = 0;
for(int i = 1; i u >> v;
g[u].emplace_back(v);
g[v].emplace_back(u);
}
dfs(1, 0);
int path = ((n * (n + 1)) / 2) % MOD, all = ((path * (path + 1)) / 2) % MOD;
ans = ((all - ans) % MOD + MOD) % MOD;
cout
关注
打赏
- 回坑记之或许是退役赛季?
- [LCT刷题] P1501 [国家集训队]Tree II
- [LCT刷题] P2147 洞穴勘测
- 2022-2023 ICPC Brazil Subregional Programming Contest VP记录
- [线段树套单调栈] 2019-2020 ICPC Asia Hong Kong Regional Contest H.[Hold the Line]
- The 2021 ICPC Asia Nanjing Regional Contest E.Paimon Segment Tree 区间合并线段树/维护矩阵乘法
- CF580E - Kefa and Watch 线段树维护哈希
- HDU5869 Different GCD Subarray Query 离线查询/区间贡献
- 27.CF1004F Sonya and Bitwise OR 区间合并线段树
- 26.CF1000F One Occurrence