Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- #define stergere copii[parinti[init][0]].erase(copii[parinti[init][0]].begin());
- using namespace std;
- vector< vector <int> > copii,parinti;
- vector<int> val,visited,inc;
- stack<int> st;
- int root,max1,n,x,t,c,s,nr;
- void DFS(int st)
- {
- for(int i=0; i<copii[st].size() ;i++)
- if(visited[copii[st][i]]==0)
- {
- visited[copii[st][i]]=visited[st]+1;
- max1=max(max1,visited[copii[st][i]]);
- DFS(copii[st][i]);
- }
- }
- void DFSSPEC(int start)
- {
- if(copii[copii[start][0]].size()==0)
- {
- st.push(start);
- s+=val[start];
- }
- else
- {
- s+=val[copii[start][0]];
- DFSSPEC(copii[start][0]);
- }
- }
- void parc(int init,vector< vector <int> > copii,vector< vector <int> > parinti)
- {
- int s=val[init];
- if(!parinti[init].empty())
- st.push(parinti[init][0]);
- stergere;
- while(!st.empty())
- {
- if(copii[st.top()].size())
- DFSSPEC(st.top());
- int cap=st.top();
- while(!copii[cap].empty())
- {
- s+=copii[cap][0];
- if(s%3==0)
- nr++;
- s-=copii[cap][0];
- copii[cap].erase(copii[cap].begin());
- }
- if(s%3==0)
- nr++;
- s-=cap;
- st.pop();
- if(parinti[parinti[cap][0]].size())
- copii[parinti[cap][0]].erase(copii[parinti[cap][0]].begin());
- }
- }
- void fct()
- {
- for(int i=1;i<=n;i++)
- if(parinti[i].empty())
- root=i;
- visited.resize(n+1);
- visited[root]=1;
- DFS(root);
- for(int i=1;i<=n;i++)
- if(visited[i]==max1)
- inc.push_back(i);
- for(int i=0;i<inc.size();i++)
- parc(inc[i],copii,parinti);
- }
- int main()
- {
- cin>>n;
- copii.resize(n+1);
- parinti.resize(n+1);
- val.push_back(0);
- for(int i=1;i<=n;i++)
- cin>>x,val.push_back(x);
- for(int i=1;i<n;i++)
- {
- cin>>t>>c;
- copii[t].push_back(c);
- parinti[c].push_back(t);
- }
- fct();
- cout<<nr;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement