当前位置:网站首页>GYM103660E.Disjoint Path On Tree 树上计数
GYM103660E.Disjoint Path On Tree 树上计数
2022-07-17 22:28:00 【HeartFireY】
GYM103660E.Disjoint Path On Tree
题目思路
给定一棵树,求树上不相交的路径对数。
容斥一下:不相交路径对数 = 总路径对数 - 相交路径对数
考虑如何计算相交路径对数:枚举点 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 <bits/stdc++.h>
#pragma gcc optimize(2)
#define int long long
#define endl '\n'
using namespace std;
const int N = 2e5 + 10, MOD = 1e9 + 7;
vector<signed> 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 <= n; i++) g[i].clear();
for(int i = 1; i <= n - 1; i++){
int u, v; cin >> 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 << ans << endl;
}
signed main(){
ios_base::sync_with_stdio(false), cin.tie(0);
int t = 1; cin >> t;
while(t--) solve();
return 0;
}
边栏推荐
- ZABBIX realizes the monitoring of redis
- 兩種虛擬機的比較
- Cross domain and CORS
- Several points to be analyzed in the domestic fpga/dsp/zynq scheme
- One article, teach you to achieve single sign on
- SQL wrong questions set of Niuke brush questions
- How to quickly realize Zadig single sign on on authoring?
- UCAS. Deep learning Final review knowledge points summary notes
- 分布式事务总结
- Oracle - lock
猜你喜欢

End repeated development and personalize the login system in twoorthree times

数据填报、报表展示哪家强?亿信ABI给你答案
![[port 3000 is already in use, solution to the problem of 3000 port being occupied]](/img/6f/6c8fdbc6b0b2794433c97e77185111.png)
[port 3000 is already in use, solution to the problem of 3000 port being occupied]

PCIe Cameralink signal generator (Cameralink image analog source)

Deployment 原理

Chang'an chain learning research - storage analysis wal mechanism

Leetcode 1275. 找出井字棋的获胜者

UCAS. Deep learning Final review knowledge points summary notes

3438. 数制转换

session管理
随机推荐
Notes on random nodes of force buckle 382 linked list
PKI:TLS握手
运行时加载 Objective-C
PCIe Cameralink signal generator (Cameralink image analog source)
Gradle introduction notes
TDesign compositionapi refactoring path
Compositionapi component development paradigm
009 面试题 SQL语句各部分的执行顺序
JVM common tuning configuration parameters
跨域与CORS
状态机练习
Is it safe to open a fund account online now?
One article, teach you to achieve single sign on
Setup的使用技巧
2021.07.13【B站】是这样崩的
Tips for using setup
Zabbix实现对Redis的监控
国科大. 深度学习. 期末试题与简要思路分析
[flask introduction series] request hook and context
LabVIEW uses multithreading. Will the program run faster