解题思路:
注意事项:
参考代码:
#include <iostream> #include <vector> using namespace std; const int N = 200010; struct Query{ int y,id; }; vector<int> v[N]; vector<Query> query[N]; int cnt[N],res[N]; int st[N],p[N],dist[N]; int n,m; int Find(int x) { if(p[x] != x) p[x] = Find(p[x]); return p[x]; } void dfs(int u,int f) { for (int i = 0; i < v[u].size(); i ++ ) { int t = v[u][i]; if(t != f) { dist[t] = dist[u] + cnt[t]; dfs(t,u); } } } void tarjan(int u) { st[u] = 1; for (int i = 0; i < v[u].size(); i ++ ) { int t = v[u][i]; if(!st[t]) { tarjan(t); p[t] = u; } } for (auto item : query[u]) { int y = item.y,id = item.id; if(st[y] == 2) { int anc = Find(y); res[id] = dist[u] + dist[y] - 2 * dist[anc] + cnt[anc]; } } st[u] = 2; } int main() { cin >> n >> m; for (int i = 1; i < n; i ++ ) { int x,y; scanf("%d%d",&x,&y); v[x].push_back(y); v[y].push_back(x); cnt[x] ++,cnt[y] ++ ; } for (int i = 1; i <= n; i ++ ) dist[i] = cnt[i]; for (int i = 1; i <= m; i ++ ) { int x,y; scanf("%d%d",&x,&y); if(x == y) { res[i] = cnt[x]; continue; } query[x].push_back({y,i}); query[y].push_back({x,i}); } dfs(1,-1); for (int i = 1; i <= n; i ++ ) p[i] = i; tarjan(1); for (int i = 1; i <= m; i ++ ) printf("%d\n",res[i]); return 0; }
0.0分
4 人评分
C语言程序设计教程(第三版)课后习题8.4 (C语言代码)浏览:631 |
C语言程序设计教程(第三版)课后习题3.7 (C语言代码)浏览:268 |
矩阵加法 (C语言代码)浏览:1768 |
C二级辅导-公约公倍 (C语言代码)浏览:537 |
IP判断 (C语言代码)浏览:592 |
C语言程序设计教程(第三版)课后习题5.7 (C语言代码)浏览:725 |
小O的数字 (C++代码)浏览:806 |
C语言程序设计教程(第三版)课后习题5.7 (C语言代码)浏览:1207 |
C语言程序设计教程(第三版)课后习题1.5 (C++代码)浏览:419 |
C二级辅导-统计字符 (C语言描述——用函数求解)浏览:1229 |