[JLOI] 树

截图于Donny_You的博客

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<set>
 4 using namespace std;
 5 const int maxn=1e5+7;
 6 int n,ss,ans;
 7 int val[maxn],sum[maxn];
 8 set < int > s;
 9 struct Edge{
10     int next,to;
11 }edge[maxn];
12 int head[maxn],num,fa[maxn];
13 void add(int from,int to){
14     edge[++num].next=head[from];
15     edge[num].to=to;
16     head[from]=num; 
17 } 
18 void dfs(int x){
19     sum[x]=sum[fa[x]]+val[x];
20     s.insert(sum[x]);
21     if(s.count(sum[x]-ss)) ans++;
22     for(int i=head[x];i;i=edge[i].next){
23         int v=edge[i].to;
24         dfs(v);
25     }
26     s.erase(sum[x]);
27 }
28 int main(){
29     cin>>n>>ss;
30     for(int i=1;i<=n;i++) cin>>val[i]; 
31     for(int i=1;i<n;i++){
32         int x,y;cin>>x>>y;
33         fa[y]=x;
34         add(x,y); 
35     }
36     s.insert(0);
37     dfs(1);
38     cout<<ans<<endl;
39     return 0;
40 }

 这个代码还没调出来:

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<bitset>
 4 using namespace std;
 5 const int maxn=1e5+7;
 6 bitset<maxn>bt;
 7 int n,s,sum,h=1,t=0,ans;
 8 int val[maxn];
 9 struct Edge{
10     int next,to;
11 }edge[maxn];
12 int head[maxn],num,q[maxn];
13 void add(int from,int to){
14     edge[++num].next=head[from];
15     edge[num].to=to;
16     head[from]=num; 
17 } 
18 void dfs(int u){
19     cout<<u<<" "<<sum<<" "<<ans<<"   "<<h<<" "<<t<<": ";
20     for(int i=h;i<=t;i++) cout<<q[i]<<" ";
21     cout<<endl; 
22     if(sum==s){
23         ans++;
24         if(head[u]){sum-=val[q[h]];h++;}
25         else return;
26     }
27     if(sum>s){
28         int he=h,su=sum;
29         while(sum>s){
30             sum-=val[q[h]];h++;
31         }
32         if(sum==s) {
33             ans++;cout<<"sum "<<sum<<" "; 
34             sum-=val[q[h]];h++;cout<<sum<<endl;
35         }
36         if(sum<s) dfs(u);
37         h=he;sum=su;
38     }
39     if(head[u]==0) return;
40     int he=h,su=sum;
41     for(int i=head[u];i;i=edge[i].next){
42         h=he;sum=su;
43         int v=edge[i].to;
44         q[++t]=v;sum+=val[v];
45         dfs(v);
46         sum-=val[v];t--;
47     }
48     return;
49 }
50 int main(){
51     cin>>n>>s;
52     for(int i=1;i<=n;i++) cin>>val[i];
53     for(int i=1;i<n;i++){
54         int x,y;cin>>x>>y;add(x,y);
55     }
56     sum=val[1];q[++t]=1;dfs(1);
57     cout<<ans<<endl;
58     return 0;
59 } 

 

posted @ 2018-08-31 09:59  lcan  阅读(139)  评论(0编辑  收藏  举报