1. HDU 4907: http://acm.hdu.edu.cn/showproblem.php? PID = 1, 4907
I won't talk about Chinese questions. Let's talk about how to solve the problem!
① The first approach is to clear all array a to zero during the competition. When the input machine executes the I-th task at the Ti time, set a [Ti] to 1 and start to input Q (indicating that there is a task request beyond the worksheet in the Q time) to write a loop, so that array a starts from a [Q, until the value of a [J] is 0 and the output J is found. This method has exceeded the time limit. However, preprocessing is performed before Q is input.
Code attached:
1 #include<stdio.h> 2 #include<string.h> 3 int t[200010],s[200010]; 4 int main() 5 { 6 int T,m,n,i,j,k,a; 7 scanf("%d",&T); 8 while(T--) 9 {10 scanf("%d%d",&m,&n);11 memset(t,0,sizeof(t));12 for(i=1; i<=m; i++)13 {14 scanf("%d",&a);15 t[a]=1;16 }17 memset(s,0,sizeof(s));18 k=1;19 for(i=1; i<=200000; i++)20 if(t[i]==0)21 {22 for(j=k; j<=i; j++)23 s[j]=i;24 k=i+1;25 }26 while(n--)27 {28 scanf("%d",&a);29 printf("%d\n",s[a]);30 }31 }32 return 0;33 }
② The second approach is the binary method. Input a [] and the lower order in the back row, and record the position where each number appears. If Q does not exist, output Q directly,
If Q exists, assuming that Q is located at POs, then the binary [POs, N ], if mid-P = A [Mid]-A [p], Left = Mid + 1; otherwise right = mid-1.
Code attached:
1 #include<iostream> 2 #include<algorithm> 3 #include<stdio.h> 4 #include<string.h> 5 using namespace std; 6 #define maxn 100010 7 int a[maxn]; 8 int main() 9 {10 int T,i;11 scanf("%d",&T);12 while(T--)13 {14 int n,m;15 scanf("%d%d",&n,&m);16 for(i=0; i<n; i++)17 scanf("%d",&a[i]);18 sort(a,a+n);19 while(m--)20 {21 int q;22 scanf("%d",&q);23 int pos=int(lower_bound(a,a+n,q)-a);24 if(pos==n||a[pos]!=q)25 printf("%d\n",q);26 else27 {28 int left=pos+1,right=n;29 while(left<right)30 {31 int mid=(left+right)>>1;32 if(a[mid]-q==mid-pos)33 left=mid+1;34 else35 right=mid;36 }37 printf("%d\n",a[left-1]+1);38 }39 }40 }41 return 0;42 }
Postscript:
The lower_bound () function is in the first and lastForward and backward openReturns values greater than or equal to Val.First elementLocation. If all elements are smaller than Val, returnLast.