bzoj 4464: [Jsoi2013]旅行时的困惑【贪心】

据说正解是有上下界最小流,但是这种1e5的玩意问什么要跑网络流啊……
贪心即可,注意一点是可以有多条路径经过一条边……
以1为根,设d[u][0/1]为u到父亲的边是向下/向上,g记录这个点儿子中不能抵消且和它的d相同(同方向)的点个数,这里的抵消是一个0和一个1可以凑一条路径直接加进答案里,在dfs儿子的时候统计一下即可

#include<iostream>
#include<cstdio>
using namespace std;
const int N=100005;
int n,h[N],cnt,d[N],f[N],g[N],ans;
struct qwe
{
    int ne,to,f;
}e[N<<1];
int read()
{
    int r=0,f=1;
    char p=getchar();
    while(p>'9'||p<'0')
    {
        if(p=='-')
            f=-1;
        p=getchar();
    }
    while(p>='0'&&p<='9')
    {
        r=r*10+p-48;
        p=getchar();
    }
    return r*f;
}
void add(int u,int v,int f)
{
    cnt++;
    e[cnt].ne=h[u];
    e[cnt].to=v;
    e[cnt].f=f;
    h[u]=cnt;
}
void dfs(int u,int fa)
{
    int s[]={0,0};
    for(int i=h[u];i;i=e[i].ne)
        if(e[i].to!=fa)
        {
            d[e[i].to]=e[i].f;
            dfs(e[i].to,u);
            s[e[i].f]+=g[e[i].to];
        }
    ans+=min(s[0],s[1]);
    if(u==1)
        ans+=max(s[0],s[1])-min(s[0],s[1]);
    else if(s[d[u]]>s[d[u]^1])
        g[u]=s[d[u]]-s[d[u]^1];
    else if(s[d[u]]<s[d[u]^1])
        ans+=s[d[u]^1]-s[d[u]];
    g[u]=max(g[u],1);
}
int main()
{
    n=read();
    for(int i=1;i<n;i++)
    {
        int x=read()+1,y=read()+1;
        add(x,y,1),add(y,x,0);
    }
    dfs(1,0);
    printf("%d\n",ans);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/lokiii/p/10780468.html