莫对算法/二分查找 FZU 2072 Count

 

题目传送门

 1 /*  2  题意:问区间内x的出现的次数  3  莫队算法:用一个cnt记录x的次数就可以了  4  还有二分查找的方法  5 */  6 #include <cstdio>  7 #include <algorithm>  8 #include <cmath>  9 #include <cstring> 10 using namespace std; 11 12 const int MAXN = 1e5 + 10; 13 const int INF = 0x3f3f3f3f; 14 struct Data 15 { 16 int b, l, r, x; 17 int id; 18 }data[MAXN]; 19 int a[MAXN]; 20 int cnt[MAXN]; 21 int ans[MAXN]; 22 int n, q; 23 24 bool cmp(Data x, Data y) 25 { 26 if (x.b == y.b) return x.r < y.r; 27 return x.b < y.b; 28 } 29 30 void Modui(void) 31 { 32 memset (cnt, 0, sizeof (cnt)); 33 34 int l = 1, r = 0; 35 for (int i=1; i<=q; ++i) 36  { 37 while (data[i].l < l) cnt[a[--l]]++; 38 while (data[i].l > l) cnt[a[l]]--, l++; 39 while (data[i].r > r) cnt[a[++r]]++; 40 while (data[i].r < r) cnt[a[r]]--, r--; 41 42 ans[data[i].id] = cnt[data[i].x]; 43  } 44 45 for (int i=1; i<=q; ++i) 46  { 47 printf ("%d\n", ans[i]); 48  } 49 } 50 51 int main(void) //FZU 2072 Count 52 { 53 // freopen ("A.in", "r", stdin); 54 55 while (scanf ("%d%d", &n, &q) == 2) 56  { 57 int block = (int) sqrt (n * 1.0); 58 for (int i=1; i<=n; ++i) scanf ("%d", &a[i]); 59 for (int i=1; i<=q; ++i) 60  { 61 scanf ("%d%d%d", &data[i].l, &data[i].r, &data[i].x); 62 data[i].b = data[i].l / block; data[i].id = i; 63  } 64 65 sort (data+1, data+1+q, cmp); 66 67  Modui (); 68  } 69 70 return 0; 71 }
 1 #include <cstdio>  2 #include <algorithm>  3 #include <cmath>  4 #include <cstring>  5 #include <vector>  6 using namespace std;  7  8 const int MAXN = 1e5 + 10;  9 const int INF = 0x3f3f3f3f; 10 int a[MAXN]; 11 int n, q; 12 vector<int> cnt[MAXN]; 13 14 int cal(int x, int r) 15 { 16 if (!cnt[x].size ()) return 0; 17 int pos = upper_bound (cnt[x].begin (), cnt[x].end (), r) - cnt[x].begin () - 1; 18 return pos; 19 } 20 21 int main(void) //FZU 2072 Count 22 { 23 // freopen ("A.in", "r", stdin); 24 25 while (scanf ("%d%d", &n, &q) == 2) 26  { 27 for (int i=1; i<=n; ++i) 28  { 29 scanf ("%d", &a[i]); 30  } 31 for (int i=1; i<=n; ++i) cnt[a[i]].clear (); 32 for (int i=1; i<=n; ++i) cnt[a[i]].push_back (i); 33 34 for (int i=1; i<=q; ++i) 35  { 36 int l, r, x; scanf ("%d%d%d", &l, &r, &x); 37 printf ("%d\n", cal (x, r) - cal (x, l - 1)); 38  } 39  } 40 41 return 0; 42 }
二分查找

 

你可能感兴趣的:(count)