/*
TLE
written by Aashray Bavisa
on 14 June 2021
*/
#include <iostream>
#include <cstdlib>
#define MARS \
ios_base::sync_with_stdio(false); \
cin.tie(NULL); \
cout.tie(NULL);
#define endl '\n'
using namespace std;
#define S ' '
#define pfor(iter, init, lim, diff) for (int iter = init; iter < lim; iter += diff)
void solve()
{
int stations, travellers;
cin >> stations >> travellers;
int train[stations];
pfor(i, 0, stations, 1)
{
cin >> train[i];
}
pfor(i, 0, travellers, 1)
{
int t;
cin >> t;
// decreased by one just to count from 0
t--;
// if desired station has train at time = 0
if (train[t])
cout << 0;
else
{
int c = 1;
bool f = 1;
while (t - c >= 0 || t + c < stations)
{
// if left side stations have train going in right side i.e. == 1
// or right side stations have traing going in left side i.e. = 2
// whenever we got first occurance of that, we got our minimum station
if ((t - c >= 0 && train[t - c] == 1) || (t + c < stations && train[t + c] == 2))
{
cout << c;
f = 0;
break;
}
c++;
}
// if couldn't find any station satisfying our condition
if (f)
cout << -1;
}
cout << S;
}
cout << endl;
}
int main()
{
MARS;
int TC = 1;
cin >> TC;
for (int u = 1; u <= TC; u++)
solve();
return 0;
}
Easy and clear solution:
simply precompute what is the closest index in left side where arr[i]==1 and
what is the closest index in right side where arr[i]==2.
You can get away with vectors but you have to use it very effectively. you cant use any of the vector functions. you have to use them just as an array. I used them to store the min time to reach of each an every station. by just taking last valid station (for both left and right) - index of the station.
This was the first time I participated in Codechef Discussions.
My experience has been so amazing this far.
I was stuck at this problem for quite a long time; not knowing it was such a silly mistake.
I appreciate that you took out time for me and tested my program!
Thank you so much
i was getting an error because i missed an edge case in which i forgot to print 0 whenever i am asked for a query on position 0.
probably this could be the reason for your code not passing. CodeChef: Practical coding for everyone here is my code.
My O(n) solution using stacks. Converted 1 to -1 and found the next greater element for all 0s and then found the previous smaller element for all 0s and then took the minimum of the two. https://www.codechef.com/viewsolution/47755461