1. 程式人生 > 實用技巧 >Max Flow

Max Flow

Farmer John has installed a new system of N?1 pipes to transport milk between the N stalls in his barn (2≤N≤50,000), conveniently numbered 1…N. Each pipe connects a pair of stalls, and all stalls are connected to each-other via paths of pipes.FJ is pumping milk between KK pairs of stalls (1≤K≤100,000). For the iith such pair, you are told two stalls sisi and titi, endpoints of a path along which milk is being pumped at a unit rate. FJ is concerned that some stalls might end up overwhelmed with all the milk being pumped through them, since a stall can serve as a waypoint along many of the KK paths along which milk is being pumped. Please help him determine the maximum amount of milk being pumped through any stall. If milk is being pumped along a path from sisi to titi, then it counts as being pumped through the endpoint stalls sisi and titi, as well as through every stall along the path between them.

給定一棵有N個點的樹,所有節點的權值都為0。
有K次操作,每次指定兩個點s,t,將s到t路徑上所有點的權值都加一。
請輸出K次操作完畢後權值最大的那個點的權值。
Input
The first line of the input contains NN and KK.
The next N-1 lines each contain two integers x and y (x≠y,x≠y) describing a pipe between stalls x and y.
The next K lines each contain two integers ss and t describing the endpoint stalls of a path through which milk is being pumped.
Output
An integer specifying the maximum amount of milk pumped through any stall in the barn.
Sample Input
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
Sample Output
9

sol:樹上差分+lca

#include<algorithm>
#include<cstring>
#include<cstdio>
using namespace std;
#define N 50005
#define sz 16
int
h[N],father[N],y,ans,tot,head[N],nxt[N*2]; int n,k,x,s,t,LCA,sum[N],size[N],f[N][sz+5],v[N*2]; void add(int x,int y){++tot;nxt[tot]=head[x];head[x]=tot;v[tot]=y;} void build(int x,int fa,int dep) { h[x]=dep;father[x]=fa; for(int i=1;i<sz;i++) f[x][i]=f[f[x][i-1]][i-1]; for(int i=head[x];i;i=nxt[i]) if(v[i]!=fa)f[v[i]][0]=x,build(v[i],x,dep+1); } int lca(int x,int y) { if(h[x]<h[y])swap(x,y); for(int i=sz-1;i>=0;i--) while(h[f[x][i]]>=h[y])x=f[x][i]; if(x==y)return x; for(int i=sz-1;i>=0;i--) if(f[x][i]!=f[y][i])x=f[x][i],y=f[y][i]; return f[x][0]; } void dfs(int x,int fa) { size[x]=sum[x]; for(int i=head[x];i;i=nxt[i]) if(v[i]!=fa)dfs(v[i],x),size[x]+=size[v[i]]; ans=max(ans,size[x]); } int main() { scanf("%d%d",&n,&k); for(int i=1;i<n;i++) scanf("%d%d",&x,&y),add(x,y),add(y,x); build(1,0,1); for(int i=1;i<=k;i++) { scanf("%d%d",&s,&t); LCA=lca(s,t); sum[s]++; //S點加1 sum[t]++; //T點加1 sum[LCA]--; //對於Lca來說,s和t都是其子結點,加了2進來了,但其實Lca這個點只加了1,所以要減1 if(LCA!=1) //如果Lca不是根,則說明Lca的父親點並沒有加1,所以要減1,因為一個點的權值和為其本身權值再加子結點權值 sum[father[LCA]]--; } dfs(1,0); printf("%d",ans); }