Pagini recente » Cod sursa (job #1532188) | Cod sursa (job #1356218) | Cod sursa (job #608110) | Cod sursa (job #1963311) | Cod sursa (job #1698954)
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
ifstream fin("heavypath.in");
ofstream fout("heavypath.out");
class ST
{
public:
ST(const vector<int> &x)
{
for (N = 1; N < int(x.size()); N <<= 1);
tree = vector<int>(2 * N, 0);
for (size_t i = 0; i < x.size(); ++i)
tree[N + i] = x[i];
for (int i = N - 1; i > 0; --i)
tree[i] = max(tree[2 * i], tree[2 * i + 1]);
}
void Update(int where, const int value)
{
tree[where += N] = value;
for (where >>= 1; where > 0; where >>= 1)
tree[where] = max(tree[2 * where], tree[2 * where + 1]);
}
int Query(int l, int r) const
{
l += N; r += N;
int vmax = 0;
while (l <= r)
{
vmax = max(vmax, max(tree[l], tree[r]));
l = (l + 1) / 2;
r = (r - 1) / 2;
}
return vmax;
}
private:
int N;
vector<int> tree;
};
vector<vector<int> > G, paths;
int V;
vector<int> v, t, nr, h, pId, pos;
vector<ST> st;
void DFS(const int x)
{
int bs = 0;
nr[x] = 1;
for ( const auto& y : G[x] )
{
if (y == t[x])
continue;
t[y] = x;
h[y] = h[x] + 1;
DFS(y);
nr[x] += nr[y];
if (bs == 0 || nr[y] > nr[bs])
bs = y;
}
if (bs == 0 )
{
pId[x] = int(paths.size());
paths.push_back(vector<int>());
}
else
pId[x] = pId[bs];
pos[x] = int(paths[pId[x]].size());
paths[pId[x]].push_back(x);
}
void BuildHeavyPath()
{
t = pId = nr = h = pos = vector<int>(V + 1);
DFS(1);
for (const auto& path : paths)
{
vector<int> pathValues;
for (int x : path)
pathValues.push_back(v[x]);
st.push_back(ST(pathValues));
}
}
int Query(int x, int y)
{
if (pId[x] == pId[y])
{
if (pos[x] > pos[y])
swap(x, y);
return st[pId[x]].Query(pos[x], pos[y]);
}
if (h[paths[pId[x]].back()] < h[paths[pId[y]].back()])
swap(x, y);
return max(st[pId[x]].Query(pos[x], int(paths[pId[x]].size()) - 1),
Query(t[paths[pId[x]].back()], y));
}
int main()
{
int M;
fin >> V >> M;
v = vector<int>(V + 1);
for (int x = 1; x <= V; ++x)
fin >> v[x];
G = vector< vector<int> >(V + 1, vector<int>());
for (int e = 1; e < V; ++e)
{
int x, y;
fin >> x >> y;
G[x].push_back(y);
G[y].push_back(x);
}
BuildHeavyPath();
int op, x, y, val;
while(M)
{
M--;
fin >> op;
if (op == 0)
{
fin >> x >> val;
v[x] = val;
st[pId[x]].Update(pos[x], val);
}
else
{
fin >> x >> y;
fout << Query(x, y) << "\n";
}
}
fin.close();
fout.close();
return 0;
}