更新个hash,1100MS。
平方和取模hash。每次最好清理一下内存。内存泄露不合适。
#include <map>
#include <set>
#include <vector>
#include <iostream>
#include <string.h>
#include <stdlib.h>
using namespace std;
#define PRIME 8887
struct Point{
int x;
int y;
Point *next;
Point():x(0),y(0),next(NULL){
}
Point(int _x,int _y):x(_x),y(_y),next(NULL){
}
};
Point *data[PRIME];
vector<Point> v;
void insert(Point &p){
int i = (p.x*p.x + p.y*p.y)%PRIME;
Point *tmp = new Point(p.x,p.y);
if(!data[i])
data[i] = tmp;
else{
tmp->next = data[i];
data[i] = tmp;
}
}
bool find(Point &p){
int i = (p.x*p.x + p.y*p.y)%PRIME;
if(!data[i])
return false;
else{
Point *t = data[i];
while(t){
if(t->x==p.x && t->y==p.y)
return true;
t = t->next;
}
return false;
}
}
void del(Point *p){
if(p==NULL)
return;
del(p->next);
delete p;
p = NULL;
}
void clear(){
for(int i=0;i<PRIME;++i){
del(data[i]);
data[i] = NULL;
}
}
void process(){
int count = 0;
if(v.size()<4){
cout<<0<<endl;
return;
}
int x1,y1,x2,y2;
for(int i=0;i<v.size()-1;++i){
for(int j=i+1;j<v.size();++j){
x1 = v[i].x;
y1 = v[i].y;
x2 = v[j].x;
y2 = v[j].y;
Point p1(x1+y2-y1,y1+x1-x2);
Point p2(x2+y2-y1,y2+x1-x2);
Point p3(x1-y2+y1,y1-x1+x2);
Point p4(x2-y2+y1,y2-x1+x2);
if(find(p1)&&find(p2))
++count;
if(find(p3) && find(p4))
++count;
}
}
cout<<count/4<<endl;
}
int main(){
int i,j;
int n;
memset(data,0,sizeof(data));
while(cin>>n,n!=0){
while(n--){
cin>>i>>j;
Point p(i,j);
insert(p);
v.push_back(p);
}
process();
clear();
v.clear();
}
return 0;
}
真不明白怎么就不能用unordered_set了,只能自己写hash。
我就用set尝试了下,3485ms。。3500ms的上限。
用set应该比自己写的二分搜索要慢,但是省事儿。后面再更新个hash。
#include <map>
#include <set>
#include <vector>
#include <iostream>
using namespace std;
class cmp{
public:
bool operator()(const pair<int,int> &p1,const pair<int,int> &p2) const{
return p1.first<p2.first|| (p1.first==p2.first&&p1.second<p2.second);
}
};
set<pair<int,int>,cmp> data;
vector<pair<int,int> > v;
void process(){
int count = 0;
if(data.size()<4){
cout<<0<<endl;
data.clear();
v.clear();
return;
}
int x1,y1,x2,y2;
for(int i=0;i<v.size()-1;++i){
for(int j=i+1;j<v.size();++j){
x1 = v[i].first;
y1 = v[i].second;
x2 = v[j].first;
y2 = v[j].second;
pair<int,int> p1(x1+y2-y1,y1+x1-x2);
pair<int,int> p2(x2+y2-y1,y2+x1-x2);
pair<int,int> p3(x1-y2+y1,y1-x1+x2);
pair<int,int> p4(x2-y2+y1,y2-x1+x2);
if(data.find(p1)!=data.end() && data.find(p2)!=data.end()){
++count;
}
if(data.find(p3)!=data.end() && data.find(p4)!=data.end()){
++count;
}
}
}
cout<<count/4<<endl;
data.clear();
v.clear();
}
int main(){
int i,j;
int n;
while(cin>>n,n!=0){
while(n--){
cin>>i>>j;
data.insert(pair<int,int>(i,j));
v.push_back(pair<int,int>(i,j));
}
process();
}
return 0;
}