【USACO15DEC】最大流Max Flow(树上差分)

听了教练的考前须知 蒟蒻紧张的要死 只想做信心题

#include<bits/stdc++.h>
#define N 50005
using namespace std;
int n,k,tot,first[N]; 
struct Tree
{
    int to,next;
}edge[2*N];
inline void addedge(int x,int y)
{
    tot++;
    edge[tot].to=y; edge[tot].next=first[x]; first[x]=tot;
}
int up[N][25],depth[N],diff[N];
void dfs1(int now,int fa)
{
    depth[now]=depth[fa]+1;
    up[now][0]=fa;
    for(int i=1;i<=21;i++)  up[now][i]=up[up[now][i-1]][i-1];
    for(int u=first[now];u;u=edge[u].next)
    {
        int vis=edge[u].to;
        if(vis==fa) continue;
        dfs1(vis,now);
    }
}
inline int lca(int x,int y)
{
    if(depth[x]<depth[y])   swap(x,y);
    for(int i=21;i>=0;i--)  if(depth[up[x][i]]>=depth[y])   x=up[x][i];
    if(x==y)    return x;
    for(int i=21;i>=0;i--)  if(up[x][i]!=up[y][i])  x=up[x][i],y=up[y][i];
    return up[x][0];
}
int ans,sum[N];
void dfs2(int now)
{
    sum[now]=diff[now];
    for(int u=first[now];u;u=edge[u].next)
    {
        int vis=edge[u].to;
        if(vis==up[now][0]) continue;
        dfs2(vis);
        sum[now]+=sum[vis];
    }
    ans=max(ans,sum[now]);
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(NULL); cout.tie(NULL);
    cin>>n>>k;
    for(int i=1,x,y;i<n;i++)
    {
        cin>>x>>y;
        addedge(x,y); addedge(y,x);
    }
    dfs1(1,0);
    for(int i=1,x,y,z;i<=k;i++)
    {
        cin>>x>>y;
        z=lca(x,y);
        diff[x]++; diff[y]++; diff[z]--; diff[up[z][0]]--;
    }
    dfs2(1);
    cout<<ans;
    return 0;
}

转载于:https://www.cnblogs.com/Patrickpwq/articles/9913795.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值