标签:
/* * Author: sweat123 * Created Time: 2016/7/13 14:46:25 * File Name: main.cpp */ #include<set> #include<map> #include<queue> #include<stack> #include<cmath> #include<string> #include<vector> #include<cstdio> #include<time.h> #include<cstring> #include<iostream> #include<algorithm> #define INF 1<<30 #define MOD 1000000007 #define ll long long #define lson l,m,rt<<1 #define key_value ch[ch[root][1]][0] #define rson m+1,r,rt<<1|1 #define pi acos(-1.0) using namespace std; const int MAXN = 80010; struct node{ int to; int next; }edge[MAXN*2]; int dp[MAXN*2][20],ind,pre[MAXN],a[MAXN],first[MAXN],rev[MAXN*2],tot,dfn[MAXN*2],vis[MAXN],fa[MAXN],n,m; void add(int x,int y){ edge[ind].to = y; edge[ind].next = pre[x]; pre[x] = ind ++; } bool cmp(int x,int y){ return x > y; } void dfs(int rt,int deq,int pa){ vis[rt] = 1; rev[++tot] = rt; fa[rt] = pa; dfn[tot] = deq; first[rt] = tot; for(int i = pre[rt]; i != -1; i = edge[i].next){ int t = edge[i].to; if(!vis[t]){ dfs(t,deq+1,rt); rev[++tot] = rt; dfn[tot] = deq; } } } int b[MAXN],cnt; void rmq(){ for(int i = 1; i <= tot; i++){ dp[i][0] = i; } for(int i = 1; i < 20; i++){ for(int j = 1; j + (1 << i) - 1 <= tot; j++){ int x = dp[j][i-1]; int y = dp[j+(1<<(i-1))][i-1]; if(dfn[x] > dfn[y]){ dp[j][i] = y; } else{ dp[j][i] = x; } } } } int lca(int x,int y){ x = first[x]; y = first[y]; if(x > y)swap(x,y); int k = (int)(log(y - x + 1) * 1.0 / log(2.0)); int l = dp[x][k]; int r = dp[y - (1<<k) + 1][k]; if(dfn[l] > dfn[r]){ return r; } else { return l; } } int main(){ while(~scanf("%d%d",&n,&m)){ for(int i = 1; i <= n; i++)scanf("%d",&a[i]); ind = 0; memset(pre,-1,sizeof(pre)); for(int i = 1; i < n; i++){ int x,y; scanf("%d%d",&x,&y); add(x,y),add(y,x); } tot = 0; memset(vis,0,sizeof(vis)); dfs(1,1,-1); rmq(); while(m --){ int k,x,y; scanf("%d%d%d",&k,&x,&y); if(k == 0){ a[x] = y; } else{ if(y > n){ printf("invalid request!\n"); continue; } cnt = 0; int tp = rev[lca(x,y)]; b[cnt++] = a[tp]; while(x != tp){ b[cnt++] = a[x]; x = fa[x]; } while(y != tp){ b[cnt++] = a[y]; y = fa[y]; } sort(b,b+cnt,cmp); if(k > cnt) printf("invalid request!\n"); else printf("%d\n",b[k-1]); } } } return 0; }
标签:
原文地址:http://www.cnblogs.com/sweat123/p/5667069.html