UVA 10474 Where is the Marble
topic: the title meaning is to give two number M and n enter m number, then enter n number, then find n number in front of the number of M is the first of the big
idea is simple, sort plus find (also can be two-point optimization).
Method One: hash, first sort, after the order to see if the previous one is the same, and then hash it, OK.
#include <iostream> #include <string.h> #include <algorithm> using namespace std;
int a[10005],hashs[10005];
int main () {int x,n,q;
int Cases=1;
while (CIN>>N>>Q) {if (n==0&&q==0) break;
memset (A,-1,sizeof (a));
memset (hashs,-1,sizeof (HASHS));
for (int i=0;i<n;i++) {cin>>a[i];
} sort (a,a+n);
Hashs[a[0]]=1;
for (int i=1;i<n;i++) {if (a[i]!=a[i-1]) {hashs[a[i]]=i+1;
}} cout<< "case#" <<cases++<< ":" <<endl;
for (int i=1;i<=q;i++) {cin>>x;
if (hashs[x]!=-1) {cout<<x<< "found at" <
Method Two: Upper_bound function with binary lookup, and lower_bound function
Upper_bound function: int pos1=upper_bound (A,A+N,X)-A; POS1 is the position of the first greater than or equal number x in the a array
Lower_bound function: int pos2=upper_bound (A,A+N,X)-A; Pos2 is the first position greater than x in the a array
with two functions to find the position of X at the same time, If the position is the same, then it proves that X is not in the a array, otherwise pos2+1 is the position of X because Lower_bound is the
that calculates the position starting from 0.
#include <iostream> #include <string.h> #include <algorithm> using namespace std;
int main () {int n,q,x;
int a[10005];
Ios::sync_with_stdio (FALSE);
int Cases=1;
while (CIN>>N>>Q) {if (n==0&&q==0) break;
cout<<100<<endl;
int qq=q;
cout<< "case#" <<cases++<< ":" <<endl;
Cout<<cases//while (qq--) {memset (a,0,sizeof (a));
for (int i=0; i<n; i++) {cin>>a[i];
B[i]=a[i];
} sort (a,a+n);
for (int i=1; i<=q; i++) {cin>>x;
/*for (int i=0; i<n; i++) cout<<a[i]<< "";
cout<<endl;*/int Pos1=upper_bound (A,A+N,X)-A;
int Pos2=lower_bound (A,A+N,X)-A; Cout<<pos1<< "* * * *" <<pos2<<endl;
if (pos1==pos2) {cout<<x<< "not found" <<endl;
} else {cout<<x<< "found at" <<pos2+1<<endl;
}}}} return 0; }