/*
分塊查找
*/
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int a[] = {5,6,7,62,4,2,53,4,6,2,5};
int n = 11;
const int upNum = 3; //3個分成一塊
int cnt = 0; //分塊的數量
int index[11];
struct indx{ //塊
int a; //塊頭
vector<int>msg; //塊內其他內容
operator < (const indx other) const{ //使用靜態的防治修改
return a < other.a;
}
}t[101];
//返回大於等於x的第一個
int tupper_bound(int x){
int left = 0, right = cnt;
int mid;
while(left <= right){
mid = (left + right) >> 1;
if(x <= t[mid].a)right = mid - 1;
else left = mid + 1;
}
return mid;
}
//建立塊表
void build(){
int ma; //塊內最大值
for(int i = 0; i < n; i++){
ma = max(a[i], ma);
if(!(i % upNum)){ //建立表頭,並初始化表內的數組下標,以及塊的表頭值
cnt++;
ma = a[i];
}
t[cnt].msg.push_back(a[i]);
t[cnt].a= ma;
}
sort(t, t + 1);
}
//查詢
int *get(int x){ //返回在第幾塊的第幾個
int ans[2];
int ans1 = tupper_bound(x); //塊間使用二分
int ans2 = -1, len = t[ans1].msg.size();
for(int i = 0; i < len; i++){
if(t[ans1].msg[i] == x)ans2 = i;
}
if(ans2 == -1)ans1 = -1;
ans[0] = ans1;
ans[1] = ans2;
return ans;
}
int main(){
build();
get(53);
return 0;
}
分塊查找
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.