zoukankan      html  css  js  c++  java
  • BZOJ4390: [Usaco2015 dec]Max Flow

    【传送门:BZOJ4390


    简要题意:

      给出一棵n个点的树,一开始所有点的点权为0,给出k个操作,每个操作输入x,y,表示将x到y的路径上的点权全部+1

      求出最大点权


    题解:

      树上差分例题,对点差分

      对于一个操作x,y,lca表示x和y的最近公共祖先,就将cf[x]++,cf[y]++,cf[lca]--,cf[fa[lca]]--

      然后从根节点dfs下去,每次先找所有子节点,然后dfs子节点,然后cf[x]+=cf[y],途中记录最大值即可


    参考代码:

    #include<cstdio>
    #include<cstring>
    #include<cstdlib>
    #include<algorithm>
    #include<cmath>
    using namespace std;
    struct node
    {
        int x,y,next;
    }a[610000];int len,last[310000];
    void ins(int x,int y)
    {
        len++;
        a[len].x=x;a[len].y=y;
        a[len].next=last[x];last[x]=len;
    }
    int bin[21],f[310000][21],dep[310000];
    void dfs(int x)
    {
        for(int i=1;bin[i]<=dep[x];i++) f[x][i]=f[f[x][i-1]][i-1];
        for(int k=last[x];k;k=a[k].next)
        {
            int y=a[k].y;
            if(y!=f[x][0])
            {
                dep[y]=dep[x]+1;
                f[y][0]=x;
                dfs(y);
            }
        }
    }
    int LCA(int x,int y)
    {
        if(dep[x]<dep[y]) swap(x,y);
        for(int i=20;i>=0;i--)
        {
            if(dep[x]-dep[y]>=bin[i])
            {
                x=f[x][i];
            }
        }
        if(x==y) return x;
        for(int i=20;i>=0;i--)
        {
            if(dep[x]>=bin[i]&&f[x][i]!=f[y][i])
            {
                x=f[x][i];y=f[y][i];
            }
        }
        return f[x][0];
    }
    int cf[310000],ans;
    void mx(int x)
    {
        for(int k=last[x];k;k=a[k].next)
        {
            int y=a[k].y;
            if(y!=f[x][0])
            {
                mx(y);
                cf[x]+=cf[y];
                ans=max(cf[x],ans);
            }
        }
    }
    int main()
    {
        bin[0]=1;for(int i=1;i<=20;i++) bin[i]=bin[i-1]<<1;
        int n,m;
        scanf("%d%d",&n,&m);
        for(int i=1;i<n;i++)
        {
            int x,y;
            scanf("%d%d",&x,&y);
            ins(x,y);ins(y,x);
        }
        f[1][0]=0;dep[1]=1;dfs(1);
        memset(cf,0,sizeof(cf));
        for(int i=1;i<=m;i++)
        {
            int x,y;
            scanf("%d%d",&x,&y);
            int lca=LCA(x,y);
            cf[x]++;cf[y]++;
            cf[lca]--;cf[f[lca][0]]--;
        }
        ans=0;
        mx(1);
        printf("%d
    ",ans);
        return 0;
    }

     

  • 相关阅读:
    LeetCode第三题:Longest Substring Without Repeating Characters
    LeetCode第二题:Add Two Numbers
    LeetCode第一题:Two Sum
    第五章 单体内置对象
    第五章 引用类型 基本包装类型
    第五章 引用类型 Function 类型
    第五章 引用类型 RegExp 类型
    第五章 引用类型 Date类型
    第五章 引用类型 Array类型
    第五章 引用类型 Object类型
  • 原文地址:https://www.cnblogs.com/Never-mind/p/8690974.html
Copyright © 2011-2022 走看看