[Title] thinking tree dp HHHOJ # 483. NOIP Sima Yi

Pay attention to the special conditions for the use of some of the topics it.

Subject to the effect

Has an n-$ $ $ a_i points a little right of the tree $, $ q $ times tree asks whether there is a length L $ $ path.

$ N, q, s \ 10 ^ 5,0 \ the a_i \ $ 2


 

Topic analysis

Do not have time to good use $ a_i \ le 2 $ conditions, that is the road dotted metaphysics.

The weight classification by parity, because each point can then be $ 0,1,2 $, so each path of the tree, adding a $ 1 $ each point, the path can be represented by his son paths +1 , changed the parity; was added a $ 2 $ each point, a path which can be represented by sub path are +2, parity preserving.

So, according to the parity into two paths each are continuous.

Then the child becomes a problem: find a tree longest path. $ F_ {i, 0/1} $ I $ $ represents a point down the chain itself comprises, parity is $ 0 / $ 1 is the longest chain length, this problem easily solved by dp.

 1 #include<bits/stdc++.h>
 2 const int maxn = 100035;
 3 const int maxm = 200035;
 4 
 5 int n,m,w[maxn],f[maxn][2],ans[2];
 6 int edgeTot,head[maxn],nxt[maxm],edges[maxm];
 7 
 8 int read()
 9 {
10     char ch = getchar();
11     int num = 0, fl = 1;
12     for (; !isdigit(ch); ch=getchar())
13         if (ch=='-') fl = -1;
14     for (; isdigit(ch); ch=getchar())
15         num = (num<<1)+(num<<3)+ch-48;
16     return num*fl;
17 }
18 void addedge(int u, int v)
19 {
20     edges[++edgeTot] = v, nxt[edgeTot] = head[u], head[u] = edgeTot;
21     edges[++edgeTot] = u, nxt[edgeTot] = head[v], head[v] = edgeTot;
22 }
23 void Max(int &x, int y){x = x>y?x:y;}
24 void dfs(int x, int fa)
25 {
26     f[x][w[x]&1] = w[x];
27     for (int i=head[x]; i!=-1; i=nxt[i])
28     {
29         int v = edges[i];
30         if (v==fa) continue;
31         dfs(v, x);
32         Max(ans[0], f[x][0]+f[v][0]);
33         Max(ans[0], f[x][1]+f[v][1]);
34         Max(ans[1], f[x][1]+f[v][0]);
35         Max(ans[1], f[x][0]+f[v][1]);
36         Max(f[x][w[x]&1], f[v][0]+w[x]);
37         Max(f[x][1-(w[x]&1)], f[v][1]+w[x]);
38     }
39     Max(ans[0], f[x][0]), Max(ans[1], f[x][1]);
40 }
41 int main()
42 {
43     memset(head, -1, sizeof head);
44     n = read(), m = read();
45     for (int i=1; i<=n; i++) w[i] = read();
46     for (int i=1; i<n; i++) addedge(read(), read());
47     dfs(1, 0);
48     for (int x; m; --m)
49     {
50         x = read();
51         puts(ans[x&1]>=x?"YES":"NO");
52     }
53     return 0;
54 }

 

 

 

END

Guess you like

Origin www.cnblogs.com/antiquality/p/11183887.html