记上一个与 相同的数的位置是 。
只考虑 , 容易发现满足题目要求即 且 ,再加上这些数在询问前面,凑成三维偏序。
然后就可以愉快的使用 cdq 分治了。
将代码中的 sort 换成手动归并排序即可使复杂度从 变为 。
#include <bits/stdc++.h>
#define lowbit(o) o & -o
#define pb push_back
#define x first
#define y second
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
const int N = 1000005;
const int mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;
const LL INF = 2e18;
struct Node{
int pos, pre, op, id, ans;
}q[N];
int a[N], ans[N];
bool cmpA(Node A,Node B)
{
if (A.pos != B.pos)
return A.pos < B.pos;
if (A.pre != B.pre)
return A.pre > B.pre;
return A.op < B.op;
}
bool cmpB(Node A,Node B)
{
if (A.pre != B.pre)
return A.pre > B.pre;
return A.op < B.op;
}
void cdq(int l,int r)
{
if (l == r)
return;
int mid = (l + r) >> 1;
cdq(l, mid), cdq(mid + 1, r);
sort(q + l, q + mid + 1, cmpB);
sort(q + mid + 1, q + r + 1, cmpB);
int j = l, mn = 1e9;
for (int i=mid+1;i<=r;i++)
{
while (j <= mid && q[j].pre >= q[i].pre)
if (!q[j].op)
mn = min(mn, q[j].pos - q[j].pre), j ++;
else
j ++;
q[i].ans = min(q[i].ans, mn);
}
}
void work()
{
int n, m;
cin>>n>>m;
map<int, int> mp;
for (int i=1;i<=n;i++)
{
cin>>a[i];
q[i] = {i, mp[a[i]], 0, 0, (int)1e9};
mp[a[i]] = i;
}
for (int i=1;i<=m;i++)
{
int l, r;
cin>>l>>r;
q[n + i] = {r, l, 1, i, (int)1e9};
}
sort(q + 1, q + n + m + 1, cmpA);
cdq(1, n + m);
for (int i=1;i<=n+m;i++)
ans[q[i].id] = q[i].ans;
for (int i=1;i<=m;i++)
if (ans[i] > 1e8)
cout << "-1\n";
else
cout << ans[i] << '\n';
}
signed main()
{
ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
int _T = 1;
//cin >> _T;
while (_T--)
work();
return 0;
}