codeforces 522D. Closest Equals 线段树+离线

题目链接

n个数m个询问, 每次询问输出给定区间中任意两个相同的数的最近距离。

先将询问读进来, 然后按r从小到大排序, 将n个数按顺序插入, 并用map统计之前是否出现过, 如果出现过, 就更新线段树。

如果当前的i等于某个询问的r, 那么就查询, 具体看代码。

 #include <iostream>
#include <vector>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <map>
#include <set>
#include <string>
#include <queue>
#include <stack>
#include <bitset>
using namespace std;
#define pb(x) push_back(x)
#define ll long long
#define mk(x, y) make_pair(x, y)
#define lson l, m, rt<<1
#define mem(a) memset(a, 0, sizeof(a))
#define rson m+1, r, rt<<1|1
#define mem1(a) memset(a, -1, sizeof(a))
#define mem2(a) memset(a, 0x3f, sizeof(a))
#define rep(i, n, a) for(int i = a; i<n; i++)
#define fi first
#define se second
typedef pair<int, int> pll;
const double PI = acos(-1.0);
const double eps = 1e-;
const int mod = 1e9+;
const int inf = ;
const int dir[][] = { {-, }, {, }, {, -}, {, } };
const int maxn = 5e5+;
int minn[maxn<<], a[maxn], ans1[maxn], ans;
struct node
{
int l, r, id;
bool operator < (node a)const
{
if(r == a.r)
id<a.id;
return r<a.r;
}
}q[maxn];
map <int, int> mp;
void pushUp(int rt) {
minn[rt] = min(minn[rt<<], minn[rt<<|]);
}
void update(int p, int val, int l, int r, int rt) {
if(l == r) {
minn[rt] = val;
return ;
}
int m = l+r>>;
if(p<=m)
update(p, val, lson);
else
update(p, val, rson);
pushUp(rt);
}
void query(int L, int R, int l, int r, int rt) {
if(L<=l&&R>=r) {
ans = min(ans, minn[rt]);
return ;
}
int m = l+r>>;
if(L<=m)
query(L, R, lson);
if(R>m)
query(L, R, rson);
}
int main()
{
int n, m;
cin>>n>>m;
for(int i = ; i<=n; i++)
scanf("%d", &a[i]);
for(int i = ; i<m; i++) {
scanf("%d%d", &q[i].l, &q[i].r);
q[i].id = i;
}
sort(q, q+m);
int pos = ;
mem2(minn);
for(int i = ; i<=n; i++) {
if(mp[a[i]]) {
update(mp[a[i]], i-mp[a[i]], , n, );
}
mp[a[i]] = i;
while(i == q[pos].r) {
ans = inf;
query(q[pos].l, i, , n, );
if(ans == inf)
ans = -;
ans1[q[pos].id] = ans;
pos++;
}
}
for(int i = ; i<m; i++)
cout<<ans1[i]<<" ";
return ;
}
上一篇:Educational Codeforces Round 47 (Div 2) (A~G)


下一篇:ios Camera学习笔记