Đề bài: Shortest Route - Submit | CodeChef
Code của em:
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<queue>
#include<string>
#define ll long long int
using namespace std;
ll lower_bound(vector<ll>& v, int x)
{
ll l = 0, r = (ll)v.size() - 1;
while (l <= r)
{
ll m = (l + r) / 2;
if (v[m] <= x) l = m + 1;
else r = m - 1;
}
if (l - 1 != -1) return v[l - 1];
return -1;
}
ll upper_bound(vector<ll>& v, int x)
{
ll l = 0, r = (ll)v.size() - 1;
while (l <= r)
{
ll m = (l + r) / 2;
if (v[m] >= x) r = m - 1;
else l = m + 1;
}
if (r + 1 != (ll)v.size()) return v[r + 1];
return -1;
}
int main()
{
int num;
ll n, m;
cin >> num;
for (int i = 0; i < num; i++)
{
cin >> n >> m;
// 1: right, 2: left
vector<ll> left_train, right_train, ans(m);
for (int j = 0; j < n; j++)
{
int x;
cin >> x;
if (x == 1) right_train.push_back(j);
else if (x == 2) left_train.push_back(j);
}
for (int j = 0; j < m; j++)
{
ll dest;
cin >> dest;
dest--;
// find the greast <= dest that has right train
// find the smallest >= dest that has left train
ll i1 = lower_bound(right_train, dest);
ll i2 = upper_bound(left_train, dest);
if (i1 == -1 && i2 == -1) ans[j] = -1;
else if (i1 == -1) ans[j] = i2 - dest;
else if (i2 == -1) ans[j] = dest - i1;
else ans[j] = min(dest - i1, i2 - dest);
}
for (int j = 0; j < m; j++) cout << ans[j] << " ";
cout << endl;
left_train.clear(); right_train.clear(); ans.clear();
}
return 0;
}
Bài này khá đơn giản nhưng không hiểu sao code của em vẫn bị WA. Giúp em với ạ!