代码如下
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <set>
#include <string>
#include <vector>
#include <queue>
#define LL long long
#define uLL unsigned long long
using namespace std;
const int N = 1e4 + 5;
const int M = 1e7 + 5;
const int INF = 0x3f3f3f3f;
int n, m, head[N], to[N], ne[N], id, w[N], x, y, z, siz[N], maxx[N], sum, a[N], root, vis[N], ans[M], cnt, tmp[N], dis[N];
bool judge[M];
void add(int x, int y, int z){
to[++id] = y, w[id] = z, ne[id] = head[x], head[x] = id;
}
void find(int u, int fa){
siz[u] = 1, maxx[u] = 0;
for (int i = head[u]; i; i = ne[i]){
if (to[i] == fa || vis[ to[i] ])
continue;
find(to[i], u);
siz[u] += siz[ to[i] ];
maxx[u] = max(maxx[u], siz[ to[i] ]);
}
maxx[u] = max(maxx[u], sum - siz[u]);
if (maxx[u] < maxx[root])
root = u;
}
void getdis(int u, int fa){
tmp[cnt++] = dis[u];
for (int i = head[u]; i; i = ne[i]){
if (to[i] == fa || vis[ to[i] ])
continue;
dis[ to[i] ] = dis[u] + w[i];
getdis(to[i], u);
}
}
void solve(int u){
queue<int> q;
for (int i = head[u]; i; i = ne[i]){
if (vis[ to[i] ])
continue;
cnt = 0;
dis[ to[i] ] = w[i];
getdis(to[i], u);
for (int j = 0; j < cnt; j++)
for (int k = 1; k <= m; k++)
if (a[k] >= tmp[j])
ans[k] |= judge[ a[k] - tmp[j] ];
for (int j = 0; j < cnt; j++){
q.push(tmp[j]);
judge[ tmp[j] ] = 1;
}
}
while (!q.empty()){
judge[ q.front() ] = 0;
q.pop();
}
}
void div(int u){
vis[u] = judge[0] = 1;
solve(u);
for (int i = head[u]; i; i = ne[i]){
if (vis[ to[i] ])
continue;
root = 0;
maxx[0] = sum = siz[ to[i] ];
find(to[i], 0);
div(root);
}
}
int main(){
scanf ("%d %d", &n, &m);
for (int i = 1; i < n; i++){
scanf("%d %d %d", &x, &y, &z);
add(x, y, z);
add(y, x, z);
}
for (int i = 1; i <= m; i++){
scanf("%d", &x);
a[++cnt] = x;
}
maxx[0] = sum = n;
find(1, 0);
div(root);
for (int i = 1; i <= m; i++)
printf("%s\n", ans[i] ? "AYE" : "NAY");
return 0;
}