洛谷 P2982 [USACO10FEB]慢下来Slowing down

每天Farmer John的N头奶牛(1 <= N <= 100000,编号1…N)从粮仓走向他的自己的牧场。牧场构成了一棵树,粮仓在1号牧场。恰好有N-1条道路直接连接着牧场,使得牧场之间都恰好有一条路径相连。第i条路连接着A_i,B_i,(1 <= A_i <= N; 1 <= B_i <= N)。 奶牛们每人有一个私人牧场P_i (1 <= P_i <= N)。粮仓的门每次只能让一只奶牛离开。耐心的奶牛们会等到他们的前面的朋友们到达了自己的私人牧场后才离开。首先奶牛1离开,前往P_1;然后是奶牛2,以此类推。

当奶牛i走向牧场P_i时候,他可能会经过正在吃草的同伴旁。当路过已经有奶牛的牧场时,奶牛i会放慢自己的速度,防止打扰他的朋友。

FJ想要知道奶牛们总共要放慢多少次速度。

输入输出格式

输入格式:
Line 1: Line 1 contains a single integer: N

Lines 2..N: Line i+1 contains two space-separated integers: A_i and B_i

Lines N+1..N+N: line N+i contains a single integer: P_i
输出格式:
Lines 1..N: Line i contains the number of times cow i has to slow down.
输入输出样例

输入样例#1:
5
1 4
5 4
1 3
2 4
4
2
1
5
3
输出样例#1:
0
1
0
2
1


【分析】
树状数组维护dfs序差分


【代码】

//洛谷 P2982 [USACO10FEB]慢下来Slowing down
#include<iostream>
#include<cmath>
#include<vector>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define M(a) memset(a,0,sizeof a)
#define fo(i,j,k) for(i=j;i<=k;i++)
using namespace std;
const int mxn=100005;
vector <int> f[mxn];
int n,m,cnt=1;
int dfn[mxn],pre[mxn],c[mxn],p[mxn];
inline int read()
{
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
inline int lowbit(int x) {return x&(-x);}
inline void add(int x,int v)
{
    for(int i=x;i<=n;i+=lowbit(i))
      c[i]+=v;
}
inline int get(int x)
{
    int sum=0;
    for(int i=x;i;i-=lowbit(i))
      sum+=c[i];
    return sum;
}
inline void dfs(int u)
{
    int i,j,x=f[u].size()-1;
    dfn[u]=cnt;
    fo(i,0,x)
    {
        int v=f[u][i];
        if(!dfn[v])
          cnt++,dfs(v);
    }
    pre[u]=cnt;
}
int main()
{
    int i,j,u,v,x,y;
    n=read();
    fo(i,2,n)
    {
        u=read(),v=read();
        f[u].push_back(v);
        f[v].push_back(u);
    }
    dfs(1);
    fo(i,1,n) p[i]=read();
    fo(i,1,n)
    {
        printf("%d\n",get(dfn[p[i]]));
        add(dfn[p[i]],1),add(pre[p[i]]+1,-1);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值