【JZOJ】【暴力】树

L i n k Link

J Z O J   2753 JZOJ\ 2753

D e s c r i p t i o n Description

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

I n p u t Input

第一行是两个整数N和S,其中N是树的节点数。

第二行是N个正整数,第i个整数表示节点i的正整数。

接下来的N-1行每行是2个整数x和y,表示y是x的儿子。

O u t p u t Output

输出路径节点总和为S的路径数量。

S a m p l e Sample I n p u t Input

3 3
1 2 3
1 2
1 3

S a m p l e Sample O u t p u t Output

2

H i n t Hint

对于30%数据,N≤100;

对于60%数据,N≤1000;

对于100%数据,N≤100000,所有权值以及S都不超过1000。

T r a i n Train o f of T h o u g h t Thought

一开始想了很多种奇妙的方法,最后发现自己都无法很完美地实现,最后无奈之下打个暴力想骗分,结果A了!(数据过水?)

C o d e Code

#include<iostream>
#include<cstring>
#include<cstdio>

using namespace std;

int N, t;
int havefa[100005], h[100005], A[100005];
long long Ans, S;

struct node
{
	int to, next;
}F[100005];

void dfs(int x, long long dep)
{
	dep += A[x];//一直叠加路径总值
	if (dep == S) {
		Ans++;
		return;
	}//达到了就给路径数加上
	else if (dep > S) return;//如果超过了目标值也就没有继续搜下去的必要了
	else {
		for (int i = h[x]; i; i = F[i].next)
			dfs(F[i].to, dep);	
	}
}

int main()
{
	scanf("%d%lld", &N, &S);
	for (int i = 1; i <= N; ++i) 
		scanf("%d", &A[i]);
	for (int i = 1; i < N; ++i)
	{
		int x, y;
		scanf("%d%d", &x, &y);
		F[++t] = (node){y, h[x]}; h[x] = t; 
		havefa[y] = 1;
	} 
	for (int i = 1; i <= N; ++i) dfs(i, 0);
    printf("%lld", Ans);
    return 0;
}  

猜你喜欢

转载自blog.csdn.net/LTH060226/article/details/104171270