gpt4 book ai didi

c++ - DFS 在 kefa 和 park 中提供 TLE(codeforces 560C)

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:37:00 24 4
gpt4 key购买 nike

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.

Examples 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

这个 dfs 算法与这个问题上许多已接受的提交非常相似,仍然得到 tle...它在自定义案例中运行良好...我无法找到它在哪里提供 TLE

#include<bits/stdc++.h>
#define ll unsigned long long int
#define ld long double
#define pb push_back
#define fillarray for(int i=0;i<n;i++)
using namespace std;

int give(auto edge,auto node,auto visited,int index,int m,int x)
{
if(edge[index].size()==1&&index!=0)
{
if(x+node[index]<=m) return 1;
else return 0;
}
if(visited[index]) return 0;
visited[index]=1;

if(node[index]) x++;
else x=0;

if(x>m) return 0;

int sum=0;
for(int i=0;i<edge[index].size();i++)
{
sum+=give(edge,node,visited,edge[index][i],m,x);
}
return sum;
}
int main()
{
int n,m;
cin>>n>>m;
vector<vector<int>> edge(n);
vector<bool> node(n);
vector<bool> visited(n,0);

fillarray{
bool x; cin>>x;
node[i]=x;
}
for(int i=0;i<n-1;i++)
{
int x,y;
cin>>x>>y;
edge[x-1].pb(y-1);
edge[y-1].pb(x-1);
}
cout<<give(edge,node,visited,0,m,0);
}

最佳答案

您需要通过引用传递:

int give(const auto& edge,const auto& node,auto& visited,int index,int m,int x)

仅通过此更改,我就通过了测试。

关于c++ - DFS 在 kefa 和 park 中提供 TLE(codeforces 560C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57751744/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com