580 DFS

题目

Kefa decided to celebrate his first big salary by going to the restaurant.

He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa’s house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.

The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats.

Your task is to help Kefa count the number of restaurants where he can go.

Input
The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa.

The second line contains n integers a1, a2, …, an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat).

Next n - 1 lines contains the edges of the tree in the format “xi yi” (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge.

It is guaranteed that the given set of edges specifies a tree.

Output
A single integer — the number of distinct leaves of a tree the path to which from Kefa’s home contains at most m consecutive vertices with cats.

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
题意:::::
给你一颗树 数的叶子那里是吃的= =..Kafe 呢从根开始走去吃吃的,但是路上连续碰到猫的数量不能超过m …..问你他可以吃到几个吃的= =.(翻译好蠢

思路呢:
1.用vector建树;
2.DFS这颗树,
递归反弹条件有两个(名词好蠢)
1.如果这个点走过或者联系碰到 meomeo的数超过m 就返回上一层(返回0,因为是无效路径??嗯呢这么表述可以嘛)
2.第二个就是碰到叶子结点返回1 一做一个吃的

嘤嘤嘤这世界上怎么会有怕喵喵的人呀

#include
#include 
using namespace std;
const int maxd =1e5+5;
int n,m;
int a[maxd];
int u,v;
int vis[maxd];
vector <int> vec[maxd];
int dfs(int cur,int meomeo)
{
    if(a[cur])
        meomeo+=1;
    else
        meomeo=0;
    if(meomeo>m||vis[cur])
        return 0; 
    vis[cur]=1; 
    int cnt=0;
    if(cur>1&&vec[cur].size()==1)
        return 1;
    for (int i=0;ireturn cnt;
}
int main ()
{
    cin>>n>>m;
    for (int i=1;i<=n;i++)
        cin>>a[i];
    for (int j= 0;j1;j++){
        cin>>u>>v;
        vec[u].push_back(v);
        vec[v].push_back(u);
    }
    cout<1,0)<return 0;
}

这道题的实质就是:在满足一定情况下 利用DFS进行遍历
那么这道题为什么用DFS呢?
首先这道题问的是根到叶子结点能不能到达的问题,
注意:根到叶子结点有且只有一条路。
而 dfs就是————–一路走到黑的典范典范典范~!!
如果和单条路径相关的话
用DFS好一些吧~

你可能感兴趣的:(stl,DFS,dfs)