AC代码:
#include <bits/stdc++.h>
using namespace std;
const int N=5e6+10;
int m,q;
struct re{
int val;
int id;
bool operator<(const re&t)const{
return val<t.val;
}
}x[N];
int ans[N];
int a[N];
int son[N];
string s;
void init(){
stack<int> st;
for(int i=0;i<s.size();i++){
if(s[i]=='?') st.push(i);
else if(s[i]==':'){
son[st.top()]=i+1;
st.pop();
}
}
}
//inline int get(string s,int p){
// int x=0;
// while(isdigit(s[p])){
// x=x*10+s[p]-'0';
// p++;
// }
// return x;
//}
void slove(int u,int l,int r){
if(l>r) return ;
if(isdigit(s[u])){
// int res=get(s,u);
int res=0;
int p=u;
while(isdigit(s[p])) res=res*10+s[p]-'0',p++;
for(int i=l;i<=r;i++) ans[x[i].id]=res;
return ;
}
int cntw=0,cntm=0;
int p1=u+2,y=0;
while(isdigit(s[p1])){
y=y*10+s[p1]-'0';
p1++;
}
int p2=son[p1];
if(s[u+1]=='>'){
int p=upper_bound(a+l,a+r+1,y)-a;
slove(p1+1,p,r);
slove(p2,l,p-1);
}else if(s[u+1]=='<'){
int p=lower_bound(a+l,a+r+1,y)-a;
slove(p1+1,l,p-1);
slove(p2,p,r);
}
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0),cout.tie(0);
cin>>m>>q;
cin>>s;
init();
for(int i=1;i<=q;i++){
cin>>x[i].val;
x[i].id=i;
}
sort(x+1,x+1+q);
for(int i=1;i<=q;i++){
a[i]=x[i].val;
}
slove(0,1,q);
for(int i=1;i<=q;i++){
cout<<ans[i]<<"\n";
}
return 0;
}
TLE:
#include <bits/stdc++.h>
using namespace std;
const int N=5e6+10;
int m,q;
struct re{
int val;
int id;
bool operator<(const re&t)const{
return val<t.val;
}
}x[N];
int ans[N];
int a[N];
int son[N];
string s;
void init(){
stack<int> st;
for(int i=0;i<s.size();i++){
if(s[i]=='?') st.push(i);
else if(s[i]==':'){
son[st.top()]=i+1;
st.pop();
}
}
}
inline int get(string s,int p){
int x=0;
while(isdigit(s[p])){
x=x*10+s[p]-'0';
p++;
}
return x;
}
void slove(int u,int l,int r){
if(l>r) return ;
if(isdigit(s[u])){
int res=get(s,u);
// int res=0;
// int p=u;
// while(isdigit(s[p])) res=res*10+s[p]-'0',p++;
for(int i=l;i<=r;i++) ans[x[i].id]=res;
return ;
}
int cntw=0,cntm=0;
int p1=u+2,y=0;
while(isdigit(s[p1])){
y=y*10+s[p1]-'0';
p1++;
}
int p2=son[p1];
if(s[u+1]=='>'){
int p=upper_bound(a+l,a+r+1,y)-a;
slove(p1+1,p,r);
slove(p2,l,p-1);
}else if(s[u+1]=='<'){
int p=lower_bound(a+l,a+r+1,y)-a;
slove(p1+1,l,p-1);
slove(p2,p,r);
}
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0),cout.tie(0);
cin>>m>>q;
cin>>s;
init();
for(int i=1;i<=q;i++){
cin>>x[i].val;
x[i].id=i;
}
sort(x+1,x+1+q);
for(int i=1;i<=q;i++){
a[i]=x[i].val;
}
slove(0,1,q);
for(int i=1;i<=q;i++){
cout<<ans[i]<<"\n";
}
return 0;
}
只是将自定义函数搬进了slove中,结果...