点的查找
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 0Sample 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;
}
相关文章推荐
- 怎样查找Xilinx的资料
- iphone下Documets目录查找
- 循环数组中查找一个数
- 【九度OJ】1029【HashMap查找】
- 利用js查找页面中的内链,外链
- 私有方法的查找方式
- 算法基础(一)------ 二分查找(折半查找)
- opecv2 MeanShift 使用均值漂移算法查找物体
- 节点查找byname
- 工作小结(十八)-Gridview使用二[在不同的地方查找Textbox和主键]
- 使用find和xargs完成查找任务
- C++用algorthm算法查找数组中是否存在的值
- 九度oj 题目1384:二维数组中的查找
- jquery根据name属性查找元素
- 编写查找一个单链表特定元素的程序。分别使用递归和非递归方法实现,并比较它们的运行时间。
- 查找与排序-----java代码分析
- C#实现局部峰值查找,功能对应Matlab中的findpeaks.m
- java实现顺序,二分,分块查找
- 应用程序/页面生命周期的理解 (问题及资料查找)
- Linux的五个查找命令:find,locate,whereis,which,type