标签:
Check if there exists a path of length l in the given tree with weight assigned to each edges.
The first line contains two integers n and q, which denote the number of nodes and queries, repectively.
The following (n−1) with three integers ai,bi,ci, which denote the edge between ai and bi, with weight ci.
Note that the nodes are labled by 1,2,…,n.
The last line contains q integers l1,l2,…,lq, denote the queries.
(1≤n,q≤105,1≤ci≤2)
For each query, print the result in seperated line. If there exists path of given length, print "Yes". Otherwise, print "No".
4 6 1 2 2 2 3 1 3 4 2 0 1 2 3 4 5
Yes Yes Yes Yes No Yes
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<cstdlib> #include<algorithm> #include<string> #include<vector> #define INF 100000000 using namespace std; vector<int> e[100005],w[100005]; int n,q; int dp[100005][2],val[2]; void dfs(int u,int father) { dp[u][0]=0; dp[u][1]=-INF; for(int i=0;i<e[u].size();i++) { int v=e[u][i]; int ww=w[u][i]; if(v==father) continue; dfs(v,u); for(int x=0;x<2;x++) { for(int y=0;y<2;y++) { val[(x+y+ww)&1]=max(val[(x+y+ww)&1],dp[u][x]+dp[v][y]+ww); } } for(int x=0;x<2;x++) dp[u][(x+ww)&1]=max(dp[u][(x+ww)&1],dp[v][x]+ww); } } int main() { scanf("%d%d",&n,&q); for(int i=1;i<n;i++) { int x,y,z; scanf("%d%d%d",&x,&y,&z); e[x].push_back(y); e[y].push_back(x); w[x].push_back(z); w[y].push_back(z); } val[0]=val[1]=-INF; dfs(1,-1); while(q--) { int x; scanf("%d",&x); if(x<0) printf("No\n"); else { if(x<=val[x&1]) printf("Yes\n"); else printf("No\n"); } } return 0; }
标签:
原文地址:http://www.cnblogs.com/water-full/p/4511296.html