二分查找
先把障碍物坐标放入一维数组中,再每次查询时,二分查找左端和右端+1的位置,如果两个迭代器相同或查找失败就返回0,否则输出答案长度。
AC 代码
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define all(a) a.begin(), a.end()
#define fi first
#define se second
#define pb push_back
#define pp pop_back
#define pf push_front
#define lb lower_bound
#define ub upper_bound
#define UNIQUE(v) sort(all(v)); v.erase(unique(all(v)), v.end())
#define all(v) v.begin(), v.end()
#define sz(v) (int)v.size()
#define PQ priority_queue
constexpr ll inf = 1e9 + 7;
void solve() {
int n, q;
cin >> n >> q;
string s;
cin >> s;
vector<int> vec;
for (int i = 0; i < n; i++) {
if (s[i] == '#') vec.pb(i+1);
}
while (q--) {
int x, y;
cin >> x >> y;
int l = min(x, y);
int r = max(x, y);
auto it1 =lb(all(vec), l);
auto it2 = ub(all(vec), r);
if (it1 == vec.end() || it1 == it2) {
cout << 0 << "\n";
continue;
}
it2--;
cout << *it2 - *it1 + 1 << "\n";
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t = 1;
while (t--) solve();
return 0;
}

京公网安备 11010502036488号