[JLOI2012]树 队列和栈

11 篇文章 0 订阅
4 篇文章 0 订阅

给定一个值 S 和一棵树。在树的每个节点有一个正整数,问有多少条路径的节点总和为S。路径中节点的深度必须是升序的。假设节点1是根节点,根的深度是0,它的儿子节点的深度为1。路径不必一定从根节点开始。

我们可以维护这样一个数据结构,他的前半部分是一个保留原来信息的队列
后半部分是一个栈
DFS一遍,当深搜到一个点时将这个点加入队列,同时队头向后调整,使队列中元素之和 <=s <script id="MathJax-Element-145" type="math/tex"><=s</script> ,等于 s 记录 ans
当一个点出栈时将队尾删除,同时队头向前调整,使队列中元素之和刚好 <=s <script id="MathJax-Element-148" type="math/tex"><=s</script>

这算是栈和队列的结合使用了……

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#define N 100000+5
#define M 200000+5
using namespace std;


int n,r,h,s;
int a[N],q[N],fa[N];
int head[N];

struct graph
{
    int next, to;
    graph() {}
    graph(int _next, int _to)
    : next(_next), to(_to) {}
} edge[M];

inline void add(int x, int y)
{
    static int cnt = 0;
    edge[++cnt] = graph(head[x], y);
    head[x] = cnt;
    edge[++cnt] = graph(head[y], x);
    head[y] = cnt;
}

int sum;
int ans ;

void DFS(int x)
{
    q[++r] = a[x];
    sum += a[x];
    while(sum>s)
        sum-=q[++h];
    if(sum==s)++ans;
    for(int i=head[x];i;i=edge[i].next)
        if(edge[i].to!=fa[x])
        {
            fa[edge[i].to] = x;
            DFS(edge[i].to);
        }
    sum-=q[r--];
    while(h && sum + q[h]<=s)
        sum += q[h--];
}

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<<1)+(x<<3)+ch-'0';ch = getchar();}
    return x*f;
}

int main()
{
    cin >> n >> s;
    for(int i=1;i<=n;++i)
        a[i] = read();
    for(int i=1;i<n;++i)
    {
        int x = read() , y = read();
        add(x,y);
    }
    DFS(1);
    cout<<ans<<endl;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值