n个数m个询问, 每次询问输出给定区间中任意两个相同的数的最近距离。
先将询问读进来, 然后按r从小到大排序, 将n个数按顺序插入, 并用map统计之前是否出现过, 如果出现过, 就更新线段树。
如果当前的i等于某个询问的r, 那么就查询, 具体看代码。
1 #include <iostream> 2 #include <vector> 3 #include <cstdio> 4 #include <cstring> 5 #include <algorithm> 6 #include <cmath> 7 #include <map> 8 #include <set> 9 #include <string> 10 #include <queue> 11 #include <stack> 12 #include <bitset> 13 using namespace std; 14 #define pb(x) push_back(x) 15 #define ll long long 16 #define mk(x, y) make_pair(x, y) 17 #define lson l, m, rt<<1 18 #define mem(a) memset(a, 0, sizeof(a)) 19 #define rson m+1, r, rt<<1|1 20 #define mem1(a) memset(a, -1, sizeof(a)) 21 #define mem2(a) memset(a, 0x3f, sizeof(a)) 22 #define rep(i, n, a) for(int i = a; i<n; i++) 23 #define fi first 24 #define se second 25 typedef pair<int, int> pll; 26 const double PI = acos(-1.0); 27 const double eps = 1e-8; 28 const int mod = 1e9+7; 29 const int inf = 1061109567; 30 const int dir[][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} }; 31 const int maxn = 5e5+5; 32 int minn[maxn<<2], a[maxn], ans1[maxn], ans; 33 struct node 34 { 35 int l, r, id; 36 bool operator < (node a)const 37 { 38 if(r == a.r) 39 id<a.id; 40 return r<a.r; 41 } 42 }q[maxn]; 43 map <int, int> mp; 44 void pushUp(int rt) { 45 minn[rt] = min(minn[rt<<1], minn[rt<<1|1]); 46 } 47 void update(int p, int val, int l, int r, int rt) { 48 if(l == r) { 49 minn[rt] = val; 50 return ; 51 } 52 int m = l+r>>1; 53 if(p<=m) 54 update(p, val, lson); 55 else 56 update(p, val, rson); 57 pushUp(rt); 58 } 59 void query(int L, int R, int l, int r, int rt) { 60 if(L<=l&&R>=r) { 61 ans = min(ans, minn[rt]); 62 return ; 63 } 64 int m = l+r>>1; 65 if(L<=m) 66 query(L, R, lson); 67 if(R>m) 68 query(L, R, rson); 69 } 70 int main() 71 { 72 int n, m; 73 cin>>n>>m; 74 for(int i = 1; i<=n; i++) 75 scanf("%d", &a[i]); 76 for(int i = 0; i<m; i++) { 77 scanf("%d%d", &q[i].l, &q[i].r); 78 q[i].id = i; 79 } 80 sort(q, q+m); 81 int pos = 0; 82 mem2(minn); 83 for(int i = 1; i<=n; i++) { 84 if(mp[a[i]]) { 85 update(mp[a[i]], i-mp[a[i]], 1, n, 1); 86 } 87 mp[a[i]] = i; 88 while(i == q[pos].r) { 89 ans = inf; 90 query(q[pos].l, i, 1, n, 1); 91 if(ans == inf) 92 ans = -1; 93 ans1[q[pos].id] = ans; 94 pos++; 95 } 96 } 97 for(int i = 0; i<m; i++) 98 cout<<ans1[i]<<" "; 99 return 0; 100 }
时间: 2024-10-10 16:13:22