To solve the problem indexes of the array are also needed to be updated and queried.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 |
#include <cstdio> #include <vector> #include <cstring> #include <algorithm> #include <iostream> using namespace std; struct RevPrime{ int reversePrime; int factorCount; }; int prime[1000001]; RevPrime arr[80000]; int Bit[2][80000]; vector<int> vb; int k=1; int reverse(int a) { int num=0; while(a) { num*=10; num += (a%10); a/=10; } return num; } bool cmp(RevPrime a,RevPrime b) { return a.reversePrime<b.reversePrime; } void update(int row,int idx,int val) { while(idx<k) { Bit[row][idx]+=val; idx +=(idx & (-idx)); } } int query(int row,int idx) { int ret=0; while(idx>0) { ret+=Bit[row][idx]; idx -= (idx & (-idx)); } return ret; } int binarySearch(int lw,int hi,int val) { if(hi<lw) return 0; int mid = (hi+lw)>>1; if(arr[mid].reversePrime<val) { return binarySearch(mid+1,hi,val); } else if(arr[mid].reversePrime>val) { return binarySearch(lw,mid,val); } else if(arr[mid].reversePrime==val) return mid; return 0; } int findIndex_bianarySearch(int lw,int hi,int modifiedIndex_value) { if(hi<lw) return 0; int mid =(hi+lw)>>1; int mid_val=query(1,mid); if(mid_val<modifiedIndex_value) return findIndex_bianarySearch(mid+1,hi,modifiedIndex_value); else if(mid_val>modifiedIndex_value) return findIndex_bianarySearch(lw,mid,modifiedIndex_value); else return mid; return 0; } int main () { int b; int tmp; for(int i=2;i<1000001;i++) { if(prime[i]==0) { prime[i]+=1; vb.push_back(i); for(int j=i+i;j<1000001;j+=i) { prime[j]+=1; tmp=j/i; while(tmp%i==0) { prime[j]+=1; tmp/=i; } } } } for(int i=0;i<vb.size();i++) { b = reverse(vb[i]); arr[k].factorCount=prime[b]; while(b<1000000) { b*=10; arr[k].factorCount+=2; } arr[k].reversePrime=b; k+=1; } sort(arr,arr+k,cmp); for(int i=1;i<k;i++) { update(0,i,arr[i].factorCount); update(1,i,1); } char ch; int n; while(scanf("%c", &ch)!=EOF) { scanf("%d",&n); if(ch=='q') { int original_index=findIndex_bianarySearch(1,k,n+1); cout<<query(0,original_index)<<"\n"; } if(ch=='d') { int idx = binarySearch(1,k,n); update(0,idx,(-1)*arr[idx].factorCount); update(1,idx,-1); } } return 0; } |