-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path62-Tree Queries.cpp
More file actions
65 lines (64 loc) · 1.36 KB
/
62-Tree Queries.cpp
File metadata and controls
65 lines (64 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include<bits/stdc++.h>
using namespace std;
vector<vector<int>>v;
vector<int>tin,tout;
int timer;
void dfs(int x,int p)
{
tin[x]=++timer;
for(auto itr:v[x])
{
if(itr!=p)
{
dfs(itr,x);
}
}
tout[x]=timer;
}
bool comp(const array<int,3>&arr1, const array<int,3>&arr2)
{
return arr1[1]<arr2[1];
}
vector<int> treeQuery(int n, vector<int> a, vector<vector<int>> edges, vector<vector<int>> queries)
{
timer=0;
tin.resize(n+1);
tout.resize(n+1,1e9);
v=vector<vector<int>>(n+1,vector<int>());
int x,y;
for(int i=0;i<edges.size();i++)
{
x=edges[i][0],y=edges[i][1];
v[x].push_back(y);
v[y].push_back(x);
}
vector<int>ans(n);
vector<array<int,3>>temp(n+2);
dfs(1,0);
temp[n+1]={0,n+5,n+1};
for(int i=1;i<=n;i++)
{
temp[i]={0,tin[i],i};
}
sort(temp.begin(),temp.end(),comp);
for(int i=0;i<queries.size();i++)
{
x=queries[i][0],y=queries[i][1];
int start=tin[x],end=tout[x];
temp[start][0]+=y;
temp[end+1][0]-=y;
}
for(int i=1;i<=n;i++)
{
temp[i][0]+=temp[i-1][0];
}
for(int i=1;i<=n;i++)
{
ans[temp[i][2]-1]=temp[i][0];
}
for(int i=0;i<n;i++)
{
ans[i]+=a[i];
}
return ans;
}