[JLOI2014]松鼠的新家题解

题目:https://www.luogu.org/problem/show?pid=3258

题解

此题与USACO Max Flow几乎是一样的(代码也几乎一样)。细节就自己想吧。

代码

#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

int n;
int toq[600100],nxtq[600100],headq[300100],totq;
int top[600100],nxtp[600100],headp[300100],totp;
int tmpfa[300100],fa[300100],record[300100],map[300100];
bool vis[300100];

void addq(int f,int t)
{
    toq[++totq] = t;
    nxtq[totq] = headq[f];
    headq[f] = totq;
}

void addp(int f,int t)
{
    top[++totp] = t;
    nxtp[totp] = headp[f];
    headp[f] = totp;
}

int find(int x){
    if(tmpfa[x] == x)return x;
    return tmpfa[x] = find(tmpfa[x]);
}

void tarjan(int pos,int pre)
{
    tmpfa[pos] = pos;
    for(int i = headp[pos];i;i = nxtp[i])
        if(top[i] != pre){
            tarjan(top[i],pos);
            tmpfa[top[i]] = pos;
        }
    vis[pos] = true;
    for(int i = headq[pos];i;i = nxtq[i])
        if(vis[toq[i]]){
            int tmp_lca = find(toq[i]);
            record[tmp_lca]--,record[fa[tmp_lca]]--,record[pos]++,record[toq[i]]++;
        }
}

void dfs(int pos,int pre)
{
    fa[pos] = pre;
    for(int i = headp[pos];i;i = nxtp[i])
        if(top[i] != pre)
            dfs(top[i],pos);
}

void dfsans(int pos,int pre)
{
    for(int i = headp[pos];i;i = nxtp[i])
        if(top[i] != pre){
            dfsans(top[i],pos);
            record[pos] += record[top[i]];
        }
}

int main()
{
    scanf("%d",&n);
    int f,t,ori;
    scanf("%d",&f);ori = f;
    for(int i = 1;i <  n;i++){
        scanf("%d",&t);
        map[t] = -1;
        addq(f,t),addq(t,f);
        f = t;
    }
    for(int i = 1;i <  n;i++){
        scanf("%d%d",&f,&t);
        addp(f,t),addp(t,f);
    }
    dfs(1,0);
    tarjan(1,0);
    dfsans(1,0);
    for(int i = 1;i <= n;i++){
        if(i == ori)
            printf("%d\n",record[i]);
        else
            printf("%d\n",record[i] - 1);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值