hdu 4366 Successor
做法:对每个人按照ability由大到小排序,把loyalty插入到线段树里面,dfs处理出每个点所在的区间,然后区间查询,单点更新。(这里学到了查询区间最大值所在id的方法)。。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 #include <cmath> 6 #include <queue> 7 #include <stack> 8 9 using namespace std; 10 11 #define LL long long 12 #define eps 1e-6 13 #define inf 0x3f3f3f3f 14 #define MP make_pair 15 #define N 250020 16 #define M 1000020 17 #pragma comment(linker, "/STACK:1024000000,1024000000") 18 #define Pi acos(-1.0) 19 #define ls (i << 1) 20 #define rs (ls | 1) 21 #define md ((ll + rr) >> 1) 22 #define lson ll, md, ls 23 #define rson md + 1, rr, rs 24 25 int fst[N], vv[N], nxt[N], e; 26 void init(){ 27 memset(fst, -1, sizeof fst); e = 0; 28 } 29 void add(int u, int v){ 30 vv[e] = v, nxt[e] = fst[u], fst[u] = e++; 31 } 32 int in[N], out[N], lab[N], dc; 33 void dfs(int u){ 34 in[u] = ++dc; 35 lab[dc] = u; 36 for(int i = fst[u]; ~i; i = nxt[i]){ 37 int v = vv[i]; 38 dfs(v); 39 } 40 out[u] = dc; 41 } 42 struct node{ 43 int id, val, loy; 44 node(){} 45 node(int _loy, int _val, int _id){ 46 loy = _loy, val = _val, id = _id; 47 } 48 bool operator < (const node &b) const{ 49 return val > b.val; 50 } 51 }b[N]; 52 53 int mx[N<<2], val[N]; 54 void build(int ll, int rr, int i){ 55 mx[i] = -1; 56 if(ll == rr) return ; 57 build(lson), build(rson); 58 } 59 void push_up(int i){ 60 if(val[mx[ls]] > val[mx[rs]]) 61 mx[i] = mx[ls]; 62 else mx[i] = mx[rs]; 63 } 64 void update(int p, int v, int ll, int rr, int i){ 65 if(ll == rr){ 66 val[ll] = v; 67 mx[i] = ll; 68 return ; 69 } 70 if(p <= md) update(p, v, lson); 71 else update(p, v, rson); 72 push_up(i); 73 } 74 int query(int l, int r, int ll, int rr, int i){ 75 if(l > r) return -1; 76 if(ll == l && r == rr) 77 return mx[i]; 78 if(r <= md) return query(l, r, lson); 79 else if(l > md) return query(l, r, rson); 80 else{ 81 int ret1 = query(l, md, lson); 82 int ret2 = query(md + 1, r, rson); 83 if(ret1 == -1) return ret2; 84 if(ret2 == -1) return ret1; 85 return val[ret1] >= val[ret2] ? ret1 : ret2; 86 } 87 } 88 89 int ans[N]; 90 int main(){ 91 int cas; 92 scanf("%d", &cas); 93 while(cas--){ 94 int n, m; 95 scanf("%d%d", &n, &m); 96 init(); 97 for(int i = 1; i < n; ++i){ 98 int u, val, loy; 99 scanf("%d%d%d", &u, &loy, &val); 100 add(u, i); 101 b[i] = node(loy, val, i); 102 } 103 dc = 0; 104 dfs(0); 105 sort(b + 1, b + n); 106 build(1, n, 1); 107 memset(val, -1, sizeof val); 108 for(int i = 1, j; i < n; i = j){ 109 j = i; 110 while(j < n && b[i].val == b[j].val){ 111 int k = b[j].id; 112 int t = query(in[k] + 1, out[k], 1, n, 1); 113 if(t == -1) ans[k] = -1; 114 else ans[k] = lab[t]; 115 j++; 116 } 117 j = i; 118 while(j < n && b[i].val == b[j].val){ 119 update(in[b[j].id], b[j].loy, 1, n, 1); 120 j++; 121 } 122 } 123 while(m--){ 124 int i; 125 scanf("%d", &i); 126 printf("%d\n", ans[i]); 127 } 128 } 129 return 0; 130 }
时间: 2024-10-13 19:26:54