codeforce580c (dfs)

本文介绍了一种使用深度优先搜索(DFS)算法解决特定路径问题的方法。在一个包含多个餐馆的树形结构中,为了避免经过连续有猫的节点,该算法计算了能到达的最大餐馆数量。代码示例详细展示了如何实现这一算法。

题目意思:给你一棵树,然后每个叶子节点会有一家餐馆,你讨厌猫,就不会走有连续超过m个节点有猫的路,然后问你最多去几家饭店

思路:直接DFS

Example

Input
4 1
1 1 0 0
1 2
1 3
1 4
Output
2
Input
7 1
1 0 1 1 0 0 0
1 2
1 3
2 4
2 5
3 6
3 7
Output
2
#include<iostream>
#include<algorithm>
#include<vector>
#include<string.h>
#include<math.h>
using namespace std;
const int maxn=1e5+6;
int flag[maxn];
vector<int>e[maxn];
int n,m,ans=0;
void dfs(int u,int num,int fa)
{
    for(int i=0;i<e[u].size();i++)
    {
        int v=e[u][i];
        if(v==fa)
        continue;
        if(flag[v]==0)
        {
            if(e[v].size()==1)
            ans++;
            dfs(v,0,u); 
        }
        else if(num+1<=m)
        {
            if(e[v].size()==1)
            ans++;
            dfs(v,num+flag[v],u);
        }
    }
}

int main()
{
    cin>>n>>m;
    for(int i=1;i<=n;i++)
    cin>>flag[i];
    for(int i=1;i<n;i++)
    {
        int u,v;
        cin>>u>>v;
        e[u].push_back(v);
        e[v].push_back(u);
    }
    dfs(1,flag[1],-1);
    cout<<ans<<endl;
}

 

转载于:https://www.cnblogs.com/xiechenxi/p/8531058.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值