洛谷 P3128 [USACO15DEC]最大流Max Flow (树上差分)

博客介绍了如何利用树上差分解决USACO15DEC比赛中的最大流问题。给定一棵连接N个隔间的树形网络,以及K条牛奶运输路线,每条路线会增加沿途隔间的运输压力。任务是找出压力最大的隔间的压力值。输入包括N和K,以及树的边和运输路线信息,输出是最大压力。树上差分在此问题中起到关键作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

FJ给他的牛棚的N(2≤N≤50,000)个隔间之间安装了N-1根管道,隔间编号从1到N。所有隔间都被管道连通了。

FJ有K(1≤K≤100,000)条运输牛奶的路线,第i条路线从隔间si运输到隔间ti。一条运输路线会给它的两个端点处的隔间以及中间途径的所有隔间带来一个单位的运输压力,你需要计算压力最大的隔间的压力是多少。

输入输出格式

输入格式:

 

The first line of the input contains NN and KK.

The next N-1N−1 lines each contain two integers xx and yy (x \ne yx≠y) describing a pipe

between stalls xx and yy.

The next KK lines each contain two integers ss and tt describing the endpoint

stalls of a path through which milk is being pumped.

 

输出格式:

 

An integer specifying the maximum amount of milk pumped through any stall in the

barn.

 

输入输出样例

输入样例#1: 复制

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

输出样例#1: 复制

9

 

给你一棵树 给你k对点 这两点之间的最短路径上的每个点权值加一 问最后最大的权值是多少

考虑树上差分,这是个裸题

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int maxn=5e4+5;
std::vector<int> G[maxn];
int dep[maxn],Fa[maxn][20],power[maxn],ans,n,m;
inline void dfs(int u,int fa)
{
	dep[u]=dep[fa]+1;Fa[u][0]=fa;
	for(int i=1;(1<<i)<=dep[u];i++)Fa[u][i]=Fa[Fa[u][i-1]][i-1];
	for(auto &v:G[u]){if(v==fa)continue;dfs(v,u);}
}
inline int lca(int x,int y)
{
	if(dep[x]<dep[y])swap(x,y);
	for(int i=19;i>=0;i--)if((1<<i)<=dep[x]-dep[y])x=Fa[x][i];
	if(x==y)return x;
    for(int i=19;i>=0;i--)if(Fa[x][i]!=Fa[y][i])x=Fa[x][i],y=Fa[y][i];
    return Fa[x][0];
}
inline void solve(int u,int fa)
{
	for(auto &v:G[u])
	{
		if(v==fa)continue;
		solve(v,u);
		power[u]+=power[v];
	}
	ans=max(ans,power[u]);
}
inline int dis(int x,int y){return dep[x]+dep[y]-dep[lca(x,y)];}
int main()
{
	scanf("%d%d",&n,&m);
	for(int i=1;i<n;i++)
	{
		int u,v;scanf("%d%d",&u,&v);
		G[u].emplace_back(v);
		G[v].emplace_back(u);
	}
	dfs(1,0);
	while(m--)
	{
		int x,y;scanf("%d%d",&x,&y);
		power[x]++;power[y]++;power[lca(x,y)]--;power[Fa[lca(x,y)][0]]--;
	}
	solve(1,0);
	printf("%d\n", ans);
	return 0;
}

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值