fork download
  1. //ZJ. Cặp số gần nhất
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4.  
  5. #define ll long long
  6. #define For(i, a, b) for(int i = a; i <= b; ++i)
  7. #define endl '\n'
  8.  
  9. const int maxn = 3e5 + 5;
  10. const int INF = 1e9;
  11.  
  12. int n, q, a[maxn], pre[maxn], bit[maxn], ans[maxn];
  13. vector<pair<int, int>> qr[maxn];
  14. unordered_map<int, int> last;
  15.  
  16. void update(int i, int val)
  17. {
  18. for(; i <= n; i += i & -i)
  19. bit[i] = min(bit[i], val);
  20. }
  21.  
  22. int get(int i)
  23. {
  24. int res = INF;
  25. for(; i > 0; i -= i & -i)
  26. res = min(res, bit[i]);
  27. return res;
  28. }
  29.  
  30. signed main()
  31. {
  32. ios_base::sync_with_stdio(false);
  33. cin.tie(NULL); cout.tie(NULL);
  34.  
  35. cin >> n >> q;
  36.  
  37. For(i, 1, n) cin >> a[i];
  38.  
  39. For(i, 1, n)
  40. {
  41. if(last.count(a[i])) pre[i] = last[a[i]];
  42. else pre[i] = 0;
  43. last[a[i]] = i;
  44. }
  45.  
  46. For(i, 1, q)
  47. {
  48. int l, r;
  49. cin >> l >> r;
  50. qr[r].push_back({l, i});
  51. }
  52.  
  53. For(i, 1, n) bit[i] = INF;
  54.  
  55. For(i, 1, n)
  56. {
  57. if(pre[i])
  58. {
  59. int pos = n - pre[i] + 1;
  60. update(pos, i - pre[i]);
  61. }
  62.  
  63. for(auto [l, id] : qr[i])
  64. {
  65. int pos = n - l + 1;
  66. ans[id] = get(pos);
  67. }
  68. }
  69.  
  70. For(i, 1, q)
  71. {
  72. if(ans[i] == INF) cout << -1 << endl;
  73. else cout << ans[i] << endl;
  74. }
  75. }
  76.  
Success #stdin #stdout 0.01s 12388KB
stdin
Standard input is empty
stdout
Standard output is empty