ACdream 1028 Path

来源:互联网 发布:骨朵网络剧排行榜 编辑:程序博客网 时间:2024/06/03 05:03

那么给出一条路径,长度为X,(X>2),我们考虑他的两端,可能全为1,可能也有2,如果把边权为2的边删掉,或者把两端边权为1的都删了,那么必然存在一条长度为X-2的边。

如果 x 是可行的,那么 (x2) 也是可行的,所以可以动态规划求出最长的奇数和偶数。注意负数的情况。

Path

Time Limit: 4000/2000MS (Java/Others)Memory Limit: 128000/64000KB (Java/Others)
SubmitStatisticNext Problem

Problem Description

Check if there exists a path of length l in the given tree with weight assigned to each edges.

Input

The first line contains two integers n and q, which denote the number of nodes and queries, repectively.

The following (n1) 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.

(1n,q105,1ci2)

Output

For each query, print the result in seperated line. If there exists path of given length, print "Yes". Otherwise, print "No".

Sample Input

4 61 2 22 3 13 4 20 1 2 3 4 5

Sample Output

YesYesYesYesNoYes

Source

ftiasch

Manager

nanae
SubmitStatistic
const int inf = 0x3f3f3f3f;const int N = 201010;int n, Q;int fa[N];int f(int x){    return x==fa[x] ? x : fa[x] = f(fa[x]);}#define UPD(x, a) x=max(x,a);int to[N], head[N], cost[N], next[N];int en;void init_edge(){    en = 0;    memset(head, -1, sizeof head);    for(int i=1; i<=n; i++) fa[i] = i;}void add(int u, int v, int w){    to[++en] = v,    cost[en] = w;    next[en] = head[u];    head[u] = en;}int down[N][2];int lim[N];void dfs(int u, int p){    down[u][0] = 0;    down[u][1] = -inf;    for(int i=head[u]; ~i; i=next[i])    {        int v = to[i], w = cost[i];        if(v == p) continue;        dfs(v, u);        for(int x = 0; x<2; x++)            for(int y=0; y<2; y++)            {                UPD(lim[x+y+w & 1], down[u][x] + down[v][y] + w);            }        for(int y=0; y<2; y++)            UPD(down[u][y+w & 1], down[v][y] + w);    }}int main(){    while (cin >> n >>Q)    {        init_edge();        for (int i=1; i<n; i++)        {            int u, v, w;            scanf("%d%d%d", &u, &v, &w);            add(u, v, w);            add(v, u, w);            fa[f(u)] = f(v);        }        lim[0] = lim[1] = -inf;        dfs(1, -1);        while (Q --)        {            int l;            scanf("%d", &l);            if (l < 0)                puts("No");            else            {                puts(l <= lim[l%2] ? "Yes" : "No");            }        }    }}


0 0
原创粉丝点击