您的位置:首页 > 移动开发 > IOS开发

点的查找

2013-11-11 20:28 253 查看

Description

平面直角坐标系上有n个点(n<100000)的点集P,现在有m个点要你判断是否在这个点集P上。

Input

只有一个案例,第一个数是n,接着有2n个数,表示n个点的坐标,然后,是一个一数m,后面有2m个点。这些点的坐标都是整数。

Ouput

按序输出这2m个点的状态,在点集P上就输出“Yes“,否则就输出“No”。

Sample Input

101 22 33 45 64 46 6056 7-8 999 9-3 -431 199 9-8 0

Sample Output

NoYesNo

思路:输入:声明一个很大的点类数组,加入是point[200000],将输入的点(x,y)放在下标为|x|的点类中即point[ |x| ],并为其申请空间。
搜索:假如检查(x0,y0)是否在之前输入的点里面,直接在point[ |x0| ]搜索是否有这个点。

代码如下  很好玩 :

#include <iostream>

#include <math.h>

using namespace std;//这个算法是模仿哈希表以及字典的算法  优点就是和快速

struct Point{
int y;
int x;
Point * next;
Point() {
next = 0;
}

};

Point *p[400001],*judge = 0;//judge是用来判断空指针(如果p[0] == judge这p[0]是空指针)

class Method{

public:
void creat(int x,int y) {
if (p[abs(x)] == judge) {
p[abs(x)] = new Point();
p[abs(x)]->x = x;
p[abs(x)]->y = y;
}else {
Point *t = p[abs(x)];
while (t->next != judge) {//if  (t指针不空)  寻找空指针
t = t->next;
}
t->next = new Point();//给空指针空间
t->next->x = x;
t->next->y = y;
}
}

int look_for(int x,int y) {//寻找点
Point *t = p[abs(x)];
while (t != judge) {//if (t不空)  
if (t->y == y && t->x == x)
return 1;
t = t->next;
}
return -1;//找不到
}

};

int main () {
Method method;
int n; 
memset(p,0,sizeof(Point *));
cin>>n;

for (int i = 0;i < n;i++) {
int x,y;
cin>>x>>y;
method.creat(x,y);
}

cin>>n;
for (i = 0;i < n;i++) {
int x,y;
cin>>x>>y;
if (method.look_for(x,y) == 1) {
cout<<"Yes"<<endl;
}
else
cout<<"No"<<endl;
}
return 0;

}

方法2: 哈希表
#include "iostream"

#include "algorithm"

#include "math.h"

struct Point{
int x;
int y;

}p[100001];

int hash[400001],next[100001];

bool look_for(int x,int y) {//查找
int value,index;
value =  abs(x+y);
index = hash[value];
while (index != -1) {
if (p[index].x == x && p[index].y == y) 
return true;
index = next[index];
}
return false;

}

using namespace std;

int main () {
int n,i,value,x,y;
memset(hash,-1,sizeof(hash));
memset(next,-1,sizeof(next));
cin>>n;
for (i = 0;i < n;i++) 
cin>>p[i].x>>p[i].y;
for (i = 0;i < n;i++) {//存入
value = abs(p[i].x + p[i].y);
next[i] = hash[value];
hash[value] = i;
}
cin>>n;
for (i = 0;i < n;i++) {
cin>>x>>y;
if (look_for(x,y))
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
}
return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  指针 算法 iostream