Cod sursa(job #2823726)

Utilizator puica2018Puica Andrei puica2018 Data 29 decembrie 2021 15:27:11
Problema Heavy Path Decomposition Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.07 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("heavypath.in");
ofstream fout("heavypath.out");

int n,m;
int v[100005];

vector <int> adj[100005];

int sz[100005],par[100005],d[100005];
int id[100005],tp[100005];
int tree[400005];

void update(int pos,int v)
{
    tree[pos+=n]=v;
    for(pos/=2; pos>0; pos/=2)
        tree[pos]=max(tree[2*pos],tree[2*pos+1]);
}

int query(int st,int dr)
{
    int res=0;
    for(st+=n,dr+=n+1; st<dr; st/=2,dr/=2)
    {
        if(st&1)
            res=max(res,tree[st++]);
        if(dr&1)
            res=max(res,tree[--dr]);
    }
    return res;
}

void dfs1(int u,int p)
{
    sz[u]=1;
    par[u]=p;
    d[u]=d[p]+1;
    for(auto v:adj[u])
    {
        if(v==p)
            continue;
        dfs1(v,u);
        sz[u]+=sz[v];
    }
}

int cnt=1;

void dfs2(int u,int p,int top)
{
    id[u]=cnt++;
    tp[u]=top;
    update(id[u],v[u]);
    int hnode=-1,hsz=-1;
    for(auto v:adj[u])
    {
        if(v==p)
            continue;
        if(sz[v]>hsz)
        {
            hsz=sz[v];
            hnode=v;
        }
    }
    if(hnode==-1)
        return;
    dfs2(hnode,u,top);
    for(auto v:adj[u])
    {
        if(v==p || v==hnode)
            continue;
        dfs2(v,u,v);
    }
}

int maxPath(int a,int b)
{
    int res=0;
    while(tp[a]!=tp[b])
    {
        if(d[tp[a]]<d[tp[b]])
            swap(a,b);
        res=max(res,query(id[tp[a]],id[a]));
        a=par[tp[a]];
    }
    if(d[a]>d[b])
        swap(a,b);
    res=max(res,query(id[a],id[b]));
    return res;
}

int main()
{
    fin>>n>>m;
    for(int i=1; i<=n; i++)
        fin>>v[i];
    for(int i=1; i<n; i++)
    {
        int a,b;
        fin>>a>>b;
        adj[a].push_back(b);
        adj[b].push_back(a);
    }
    dfs1(1,0);
    dfs2(1,0,1);
    while(m--)
    {
        int t,x,y;
        fin>>t>>x>>y;
        if(t==0)
        {
            v[x]=y;
            update(id[x],y);
        }
        else
            fout<<maxPath(x,y)<<"\n";
    }
    return 0;
}