POJ 2104 - K-th Number 【开坑!
先来朴素的排序解法:
1 #include <cstdio> 2 #include <algorithm> 3 using namespace std; 4 5 struct D { 6 int pos, val; 7 } sorted[100000]; 8 9 int cmp(const struct D &a, const struct D &b) 10 { 11 return a.val < b.val; 12 } 13 14 int main(void) 15 { 16 int N, M; 17 scanf("%d%d", &N, &M); 18 for(int i=0; i<N; ++i) { 19 scanf("%d", &sorted[i].val); 20 sorted[i].pos = i + 1; 21 } 22 sort(sorted, sorted + N, cmp); 23 24 for(int c=0; c<M; ++c) { 25 int i, j, k; 26 scanf("%d%d%d", &i, &j, &k); 27 int u; 28 for(u=0; u<N; ++u) 29 if (sorted[u].pos >= i && sorted[u].pos <= j) 30 if (!--k) break; 31 printf("%d\n", sorted[u].val); 32 } 33 return 0; 34 }
2104 | Accepted | 1140K | 6625MS | G++ | 605B | 2014-07-24 11:06:26 |
然后特地学了主席树(还不会套树状数组):
1 #include <cstdio> 2 #include <algorithm> 3 using namespace std; 4 5 #define MAXN 100007 6 7 int a[MAXN], mapa[MAXN], QN; 8 9 int lsi[MAXN*100], rsi[MAXN*100], v[MAXN*100], totv; 10 11 #define lsn l, m 12 #define rsn m+1, r 13 14 int build(int l, int r) 15 { 16 int root = totv++; 17 v[root] = 0; 18 if (l == r) { 19 lsi[root] = rsi[root] = 0; 20 return root; 21 } 22 int m = (l + r) >> 1; 23 build(lsn); build(rsn); 24 return root; 25 } 26 27 int lshift(int T, int p) 28 { 29 int root, t; 30 root = t = totv++; 31 int l = 0, r = QN - 1; 32 while(l < r) { 33 v[t] = v[T] + 1; 34 int m = (l+r) >> 1; 35 if (p <= m) { 36 lsi[t] = totv++, rsi[t] = rsi[T]; 37 T = lsi[T], t = lsi[t], r = m; 38 } else { 39 rsi[t] = totv++, lsi[t] = lsi[T]; 40 T = rsi[T], t = rsi[t], l = m + 1; 41 } 42 } 43 v[t] = v[T] + 1; 44 return root; 45 } 46 47 int query(int Tl, int Tr, int k) 48 { 49 int l = 0, r = QN-1; 50 while(l < r) { 51 int m = (l+r) >> 1; 52 if (v[lsi[Tl]] - v[lsi[Tr]] >= k) 53 Tl = lsi[Tl], Tr = lsi[Tr], r = m; 54 else { 55 k -= v[lsi[Tl]] - v[lsi[Tr]]; 56 Tl = rsi[Tl], Tr = rsi[Tr], l = m+1; 57 } 58 } 59 return l; 60 } 61 62 int T[MAXN + 1]; 63 64 int main(void) 65 { 66 int N, M; 67 scanf("%d%d", &N, &M); 68 for(int i=0;i<N; ++i) { 69 scanf("%d", &a[i]); 70 mapa[i] = a[i]; 71 } 72 sort(mapa, mapa + N); 73 QN = unique(mapa, mapa + N) - mapa; 74 T[N] = build(0, QN-1); 75 for(int i=N; i-->0;) { 76 a[i] = lower_bound(mapa, mapa + QN, a[i]) - mapa; 77 T[i] = lshift(T[i+1], a[i]); 78 } 79 for(int u=0; u<M; ++u) { 80 int i, j, k; 81 scanf("%d%d%d", &i, &j, &k); 82 printf("%d\n", mapa[query(T[i-1], T[j], k)]); 83 } 84 return 0; 85 }
2104 | Accepted | 24700K | 1610MS | G++ | 1577B | 2014-07-24 14:05:17 |
看到时间差距了?
This article is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
本文采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。