参考习题
CCF 201912-2 回收站选址
普通版
#include<stdio.h> #include<algorithm> const int N=5e3+5; int n,px[N],py[N],cnt[5]; struct dat{ int x,y; dat(int x=0,int y=0):x(x),y(y){} bool operator <(const dat &a)const{ return x!=a.x?x<a.x:y<a.y; } bool operator ==(const dat &a)const{ return x==a.x&&y==a.y; } }po[N]; inline int search(int x,int y){ int p=std::lower_bound(po+1,po+n+1,dat(x,y))-po; return po[p]==dat(x,y); } inline int judge(const int &x,const int &y){ if(!search(x-1,y)) return 0; if(!search(x+1,y)) return 0; if(!search(x,y-1)) return 0; if(!search(x,y+1)) return 0; return 1; } inline int calc(const int &x,const int &y){ return search(x-1,y-1)+search(x+1,y-1)+search(x-1,y+1)+search(x+1,y+1); } int main(){ scanf("%d",&n); for(int i=1;i<=n;i++) scanf("%d%d",px+i,py+i),po[i]=dat(px[i],py[i]); std::sort(po+1,po+n+1); for(int i=1,t;i<=n;i++){ if(judge(px[i],py[i])){ t=calc(px[i],py[i]); cnt[t]++; } } for(int i=0;i<5;i++) printf("%d ",cnt[i]); return 0; }
set版
#include<stdio.h> #include<set> #include<algorithm> #define mp make_pair using namespace std; const int N=5e3+5; int n,px[N],py[N],cnt[5]; set<pair<int,int>>s; inline int search(int x,int y){ return s.find(mp(x,y))!=s.end(); } inline int judge(const int &x,const int &y){ if(!search(x-1,y)) return 0; if(!search(x+1,y)) return 0; if(!search(x,y-1)) return 0; if(!search(x,y+1)) return 0; return 1; } inline int calc(const int &x,const int &y){ return search(x-1,y-1)+search(x+1,y-1)+search(x-1,y+1)+search(x+1,y+1); } int main(){ scanf("%d",&n); for(int i=1;i<=n;i++) scanf("%d%d",px+i,py+i),s.insert(mp(px[i],py[i])); for(int i=1,t;i<=n;i++){ if(judge(px[i],py[i])){ t=calc(px[i],py[i]); cnt[t]++; } } for(int i=0;i<5;i++) printf("%d ",cnt[i]); return 0; }
二维(/多维)坐标转换字符串 哈希
hash<x,y> x必须是基本类型,包括string ; y可以是自定义类型,需要重载‘()’
#include<stdio.h> #include<sstream> #include<ext/pb_ds/assoc_container.hpp> using namespace std; using namespace __gnu_pbds; cc_hash_table<string,int> hs; const int N=5e3+5; int n,px[N],py[N],cnt[5]; string str; inline string getxy(int x,int y){ string ts=""; stringstream ss; ss<<x<<"&"<<y; // ss.clear();//before every change // ss.str("");//be zero ss>>ts; return ts; } inline int search(int x,int y){ string s=getxy(x,y); return hs[s]; } inline int judge(const int &x,const int &y){ if(!search(x-1,y)) return 0; if(!search(x+1,y)) return 0; if(!search(x,y-1)) return 0; if(!search(x,y+1)) return 0; return 1; } inline int calc(const int &x,const int &y){ return search(x-1,y-1)+search(x+1,y-1)+search(x-1,y+1)+search(x+1,y+1); } int main(){ scanf("%d",&n); for(int i=1;i<=n;i++) scanf("%d%d",px+i,py+i),str=getxy(px[i],py[i]),hs[str]=1; for(int i=1,t;i<=n;i++){ if(judge(px[i],py[i])){ t=calc(px[i],py[i]); cnt[t]++; } } for(int i=0;i<5;i++) printf("%d ",cnt[i]); return 0; }