my solution was giving TLE. Please help me out with this.
#include <bits/stdc++.h>
using namespace std;
int main() {
// your code goes here
ios_base::sync_with_stdio(false);
cin.tie(NULL);
long long t;
cin>>t;
for(long long i=0;i<t;i++)
{
string s;
cin>>s;
long long n=s.length();
long long q;
cin>>q;
vector <long long> tim(n+1,0);
stack < pair <char ,long long > > st;
st.push({'a',0});
for(long long j=0;j<n;j++)
{
if(s[j]==')')
{
if((st.top()).first=='a')
continue;
else
{
tim[(st.top()).second]=j+1;
st.pop();
}
}
else
{
st.push({s[j],j+1});
tim[j+1]=j+1;
}
}
while((st.top()).first!='a')
st.pop();
long long ind=0,index=0;
for(long long j=n;j>0;j--)
{
if(tim[j]!=0 && tim[j]!=j)
{
ind=tim[j];
index=j;
break;
}
}
for(long j=index-1;j>0;j--)
{
if(tim[j]==0)
{
tim[j]=ind;
}
else
{
if(tim[j]!=j)
ind=tim[j];
}
}
for(long long j=0;j<q;j++)
{
long long tm;
cin>>tm;
if(tim[tm]==tm)
cout<<-1<<endl;
else
{
if(tim[tm]!=0)
cout<<tim[tm]<<endl;
else
cout<<-1<<endl;
}
}
}
return 0;
}