题目链接
这道题是Geohash得模板题,至于什么是Geohash,网上不管是博客,还是维基百科,解释都够详细了,当然还有这道题的提示里也解释的很详细了(比较推荐看题目里的解释,不但详细,还有伪码模板),大致就是用经纬度描述地点时,将经纬度通过二分转化为为二进制编码,然后按先经度后维度,再经度再维度........的顺序将两二进制编码合并,接着每5位给出其对应的十进制数,再通过base32表得出对应的Geohash。这道题就是完全不用动脑子的套模板啦。
#include
#include
#include
#include
#include
using namespace std;
#define clegh 10//geohash编码长度
char Base32[32]= {'0','1','2','3','4','5','6','7','8','9','b',
'c','d','e','f','g','h','j','k','m','n','p',
'q','r','s','t','u','v','w','x','y','z'
};//Base32编码
char geohash[15]= {'\0'};
void encode(double lat,double lot,int prec)//译码
{
memset(geohash,'\0',sizeof(geohash));
double latitude[2] = {-90, 90};
double logitude[2] = {-180, 180};
int length = prec * 5; // 需要的二进制编码长度
int bits = 0 ;// 记录二进制码
int k=0;
for(int i=0; i mid)
{
bits=bits*2+1;
logitude[0] = mid;
}
else
{
bits=bits*2;
logitude[1] = mid;
}
}
else
{
double mid = (latitude[0] + latitude[1]) / 2;
if(lat > mid)
{
bits=bits*2+1;
latitude[0] = mid;
}
else
{
bits=bits*2;
latitude[1] = mid;
}
}
if(!((i+1)%5))
{
geohash[k++] = Base32[bits];
//printf("%d\n",bits);
bits = 0;// 重置二进制码
}
}
}
double lat=0, lot=0;
void docode(char *geoh)//解码
{
bool odd = true ;// 当前计算位的奇偶性
double latitude[2] = {-90, 90};
double longitude[2] = {-180, 180};
for(int i=0; i=0; j--)
{
int bit = (bits >> j) & 1 ;// 通过位运算取出对应的位
if(odd)
{
double mid = (longitude[0] + longitude[1]) / 2;
longitude[1 - bit] = mid;
}
else
{
double mid = (latitude[0] + latitude[1]) / 2;
latitude[1 - bit] = mid;
}
odd = !odd;
}
}
lat = (latitude[0] + latitude[1]) / 2;
lot = (longitude[0] + longitude[1]) / 2;
}
int main()
{
//freopen("in.in","r",stdin);
int n, m;
scanf("%d%d",&n,&m);
for(int i=1; i<=n; i++)
{
scanf("%lf%lf",&lat,&lot);
//printf("%lf %lf\n",lat,lot);
encode(lat,lot,clegh);
printf("%s\n",geohash);
}
char c=getchar();
memset(geohash,'\0',sizeof(geohash));
for(int i=1; i<=m; i++)
{
scanf("%s",geohash);
c=getchar();
//printf("%s\n",geohash);
docode(geohash);
printf("%lf %lf\n",lat,lot);
}
return 0;
}