[CEOI 2022] Homework
题目分析
首先注意到答案构成一个连续值域区间。考虑扔到表达式树上,对每个子树考虑完之后推出当前节点。
我们规定有值的节点是
对于
考虑
考虑
这样就可以递推出来根的最大最小了。
时间复杂度
代码
#include<bits/stdc++.h>
using namespace std;
constexpr int N=1e7+1;
int n,rt,val[N][2];
string s;
struct TreeNode{
int type,ls,rs,siz;
}f[N];
int build(int start,const string&command,int&cur){
cur=(++n);
if(command[start]=='?'){
f[cur].type=0,f[cur].siz=1;
do start++;
while(start<command.size()&&(command[start]==','||command[start]==')'));
return start;
}
if(command[start+1]=='i')
f[cur].type=-1;
else
f[cur].type=1;
int ret=build(build(start+4,command,f[cur].ls),command,f[cur].rs);
f[cur].siz=f[f[cur].ls].siz+f[f[cur].rs].siz;
return ret;
}
void dfs(int u){
if(!f[u].type){
val[u][0]=val[u][1]=1;
return;
}
dfs(f[u].ls),dfs(f[u].rs);
if(f[u].type>0)
val[u][1]=max(val[f[u].ls][1]+f[f[u].rs].siz,f[f[u].ls].siz+val[f[u].rs][1]),
val[u][0]=val[f[u].ls][0]+val[f[u].rs][0];
else
val[u][1]=val[f[u].ls][1]+val[f[u].rs][1]-1,
val[u][0]=min(val[f[u].ls][0],val[f[u].rs][0]);
return;
}
int main(){
cin>>s;
build(0,s,rt);
dfs(rt);
cout<<val[rt][1]-val[rt][0]+1;
return 0;
}