fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int MaxN=1e5;
  5. const int MaxA=1e5;
  6.  
  7. int N;
  8. int qry[MaxN]; // 老師的手牌
  9. int num[MaxN]; // 學生的手牌
  10. int pos[MaxA+1];
  11. int ansL[MaxN]; // ansL[x]=從位置x往左看時
  12. int ansR[MaxN]; // ansR[x]=從位置x往右看時
  13.  
  14. int func(int a,int b){
  15. return (b==-1)? 1e9: abs(a-b); }
  16.  
  17. int main(){
  18. cin>>N;
  19. for(int n=0; n<N; n+=1)
  20. cin>>qry[n];
  21. for(int n=0; n<N; n+=1)
  22. cin>>num[n];
  23. // 由左而右掃描,每個位置向左看時
  24. for(int a=1; a<=MaxA; a+=1)
  25. pos[a]=-1;
  26. for(int n=0; n<N; n+=1){
  27. pos[ num[n] ]=n;
  28. ansL[n]=pos[ qry[n] ];
  29. }
  30. //由右而左掃描,每個位置向右看時
  31. for(int a=1; a<=MaxA; a+=1)
  32. pos[a]=-1;
  33. for(int n=N-1; 0<=n; n-=1){
  34. pos[ num[n] ]=n;
  35. ansR[n]=pos[ qry[n] ];
  36. }
  37. //
  38. for(int n=0; n<N; n+=1){
  39. int L=func(n,ansL[n]);
  40. int R=func(n,ansR[n]);
  41. cout<<( min(L,R)==1e9 ? -1: min(L,R) ) <<" ";
  42. }
  43. }
Success #stdin #stdout 0.01s 5292KB
stdin
6
1 3 5 2 4 2
1 9 2 4 5 6
stdout
0 -1 2 1 1 3