【图论】树上差分(点差分)

一.题目

输入样例:

5 10

3 4

1 5

4 2

5 4

5 4

5 4

3 5

4 3

4 3

1 3

3 5

5 4

1 5

3 4

输出样例:9


二 .分析

我们可以先建一棵树

但我们发现,这样会超时。

所以,我们想到树上差分

三.代码

cpp 复制代码
/*
5 10
3 4
1 5
4 2
5 4
5 4
5 4
3 5
4 3
4 3
1 3
3 5
5 4
1 5 
3 4
*/

#include<bits/stdc++.h>
#define maxn 500005
using namespace std;
int n,m;
int head[maxn],depth[maxn],p[maxn][25],d[maxn];
struct Edge{
	int u,v,next;
}edge[maxn<<1];
int cnt=0;
void add(int u,int v){
	edge[++cnt]=(Edge){u,v,head[u]}; head[u]=cnt;
}
void dfs(int u,int fa){
	depth[u]=depth[fa]+1;
	p[u][0]=fa;
	for(int i=1;(1<<i)<=depth[u];i++){
		p[u][i]=p[p[u][i-1]][i-1];
	}
	for(int i=head[u];i;i=edge[i].next){
		int v=edge[i].v;
		if(v!=fa){
			dfs(v,u);
		}
	}
}
int lca(int x,int y){
	if(depth[x]<depth[y]) swap(x,y);
	int lg=0;
	while((1<<lg)<=depth[x]) lg++;
	for(int i=lg;i>=0;i--){
		if(depth[x]-(1<<i)>=depth[y]) x=p[x][i];
	}
	if(x==y) return x;
	for(int i=lg;i>=0;i--){
		if(p[x][i]!=p[y][i]){
			x=p[x][i]; y=p[y][i];
		}
	}
	return p[x][0];
}
void dfs2(int u,int fa){
	for(int i=head[u];i;i=edge[i].next){
		int v=edge[i].v;
		if(v!=fa){
			dfs2(v,u);
			d[u]+=d[v];
		}
	}
}
int main(){
	cin>>n>>m;
	for(int i=1;i<=n-1;i++){
		int u,v;cin>>u>>v;add(u,v);add(v,u);
	}
	dfs(1,0); //建树 
	while(m--){
		int u,v; cin>>u>>v;
		d[u]++; d[v]++;
		int lc=lca(u,v);
		d[lc]--; d[p[lc][0]]--;
	}
	dfs2(1,0); //sum求原数组 
	int ans=0;
	for(int i=1;i<=n;i++){
		ans=max(ans,d[i]);
	}
	cout<<ans;
	return 0;
}
相关推荐
罗西的思考25 分钟前
DreamZero 与 DreamDojo:世界模型与策略的分层协同综合分析与对比
人工智能·算法·机器学习
玖玥拾1 小时前
LeetCode 219 存在重复元素 II
算法·leetcode·哈希算法·散列表
知无不研2 小时前
c语言中循环的介绍与简单应用
c语言·开发语言·算法·循环·for·while
a187927218313 小时前
【算法】动态规划第四篇:背包收官——min 哨兵、计数世界与组合排列分水岭
算法·leetcode·动态规划·dp·01背包·算法讲解·决策合并
2601_962297483 小时前
在python3中、下列输出变量a的正确写法是_2020超星大数据Python免费答案
数据结构·python·算法·编程·字符串操作
辰烨chenye4 小时前
LeetCode Hot 100 题解 · 子串篇
算法·leetcode·职场和发展
辰烨chenye4 小时前
LeetCode Hot 100 题解 · 堆篇
java·算法·leetcode
手写码匠4 小时前
华为云Flexus+DeepSeek征文|DeepSeek 应用监控告警体系实战:从“用户投诉才知道“到“故障前就发现“
人工智能·深度学习·算法·aigc
shehuiyuelaiyuehao4 小时前
算法29,前缀和,除自身以外的数组的乘积
java·数据结构·算法
智购科技自动售货机厂家5 小时前
2026自动售货机设备清洁效果自动验证:从图像比对到评分算法的工程实践~YH
人工智能·算法·计算机视觉