给一棵树, m个操作, 一共两种操作, 将第x个点的权值改为y, 询问x->y路径上权值第k大的点的权值。
暴力的找.....
1 #include <iostream> 2 #include <vector> 3 #include <cstdio> 4 #include <cstring> 5 #include <algorithm> 6 #include <cmath> 7 #include <map> 8 #include <set> 9 #include <string> 10 #include <queue> 11 #include <stack> 12 #include <bitset> 13 using namespace std; 14 #define pb(x) push_back(x) 15 #define ll long long 16 #define mk(x, y) make_pair(x, y) 17 #define lson l, m, rt<<1 18 #define mem(a) memset(a, 0, sizeof(a)) 19 #define rson m+1, r, rt<<1|1 20 #define mem1(a) memset(a, -1, sizeof(a)) 21 #define mem2(a) memset(a, 0x3f, sizeof(a)) 22 #define rep(i, n, a) for(int i = a; i<n; i++) 23 #define fi first 24 #define se second 25 typedef pair<int, int> pll; 26 const double PI = acos(-1.0); 27 const double eps = 1e-8; 28 const int mod = 1e9+7; 29 const int inf = 1061109567; 30 const int dir[][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} }; 31 const int maxn = 1e5+5; 32 int head[maxn*2], num, f[maxn], deep[maxn], n, val[maxn]; 33 struct node 34 { 35 int to, nextt; 36 }e[maxn*2]; 37 void add(int u, int v) { 38 e[num].to = v, e[num].nextt = head[u], head[u] = num++; 39 } 40 void init() { 41 num = 0; 42 mem1(head); 43 } 44 void dfs(int u, int fa) { 45 f[u] = fa; 46 for(int i = head[u]; ~i; i = e[i].nextt) { 47 int v = e[i].to; 48 if(v == fa) 49 continue; 50 deep[v] = deep[u]+1; 51 dfs(v, u); 52 } 53 } 54 int lca(int k, int a, int b) 55 { 56 int i,j; 57 vector <int> v; 58 if(deep[a]<deep[b]) 59 swap(a, b); 60 while(deep[a]>deep[b]) { 61 v.pb(val[a]); 62 a = f[a]; 63 } 64 while(a!=b) { 65 v.pb(val[a]); 66 v.pb(val[b]); 67 a = f[a]; 68 b = f[b]; 69 } 70 v.pb(val[a]); 71 if(k>v.size()) 72 return -1; 73 sort(v.begin(), v.end()); 74 reverse(v.begin(), v.end()); 75 return v[k-1]; 76 } 77 int main() 78 { 79 int x, y, m, w, z, sign; 80 while(cin>>n>>m) { 81 init(); 82 for(int i = 1; i<=n; i++) 83 scanf("%d", &val[i]); 84 for(int i = 0; i<n-1; i++) { 85 scanf("%d%d", &x, &y); 86 add(x, y); 87 add(y, x); 88 } 89 dfs(1, 0); 90 while(m--) { 91 scanf("%d%d%d", &sign, &x, &y); 92 if(!sign) { 93 val[x] = y; 94 } else { 95 int ans = lca(sign, x, y); 96 if(~ans) 97 cout<<ans<<endl; 98 else 99 puts("invalid request!"); 100 } 101 } 102 } 103 return 0; 104 }
时间: 2024-10-17 17:37:16