标签:
6 4 23 34 46 768 343 343 2 4 23 343
NO NO YES YES
题解:hash表,以内存换空间;MOD越大,越耗内存,运行时间越短;
hash代码;
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<set> using namespace std; #define mem(x,y) memset(x,y,sizeof(x)) const int MOD=5000010; const int MAXN=5000010; int top; int hash[MAXN],next[MAXN],head[MAXN]; void add(int x){ int i=x%MOD; hash[top]=x; next[top]=head[i]; head[i]=top++; } int main(){ int m,n; scanf("%d%d",&m,&n); mem(head,-1);mem(next,0);mem(hash,0); int x; top=0; while(m--){ scanf("%d",&x); add(x); } while(n--){ scanf("%d",&x); int flot=0; for(int i=head[x%MOD];i!=-1;i=next[i]){ if(hash[i]==x){ flot=1;break; } } if(flot)puts("YES"); else puts("NO"); } return 0; }
二分:
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<cmath> 5 #include<algorithm> 6 #include<set> 7 using namespace std; 8 #define mem(x,y) memset(x,y,sizeof(x)) 9 typedef long long LL; 10 const int MAXN=1000010; 11 int l[MAXN]; 12 bool erfen(int le,int r,int x){ 13 int mid; 14 int flot=0; 15 while(le<=r){ 16 mid=(le+r)>>1; 17 if(l[mid]==x)return true; 18 if(l[mid]>x)r=mid-1; 19 else le=mid+1; 20 } 21 return false; 22 } 23 int main(){ 24 int m,n; 25 scanf("%d%d",&m,&n); 26 for(int i=0;i<m;i++)scanf("%d",l+i); 27 sort(l,l+m); 28 int x; 29 while(n--){ 30 scanf("%d",&x); 31 if(erfen(0,m-1,x))puts("YES"); 32 else puts("NO"); 33 } 34 return 0; 35 }
set:
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<set> using namespace std; #define mem(x,y) memset(x,y,sizeof(x)) typedef long long LL; set<LL>st; const int MAXN=1000010; int main(){ int m,n; scanf("%d%d",&m,&n); st.clear(); int x; while(m--){ scanf("%d",&x); st.insert(x); } while(n--){ scanf("%d",&x); if(st.find(x)!=st.end())puts("YES"); else puts("NO"); } return 0; }
标签:
原文地址:http://www.cnblogs.com/handsomecui/p/4979211.html