题目
分析
- 首先要观察一下这个树,
只有叶节点是变量,其他是表达式。 - 那么思考一个问题, x + ( y + z ) = x + y + z x+(y+z)=x+y+z x+(y+z)=x+y+z ,也就是说如果一个节点的子节点的符号和自己的符号一样,那么我们可以把它们放在同一层 。
- 然后考虑一下 m a x ( t 1 , t 2 ) + t 0 max(t_1,t_2)+t_0 max(t1,t2)+t0 这个式子的性质,加上我们上一个发现的性质,我们现在面对的问题就是,如何在n个元素中,两两配对取最大值后累加的最小值,显然我们按顺序两两配对即可,然后连续操作,直到只剩一个元素了。
- 这里需要注意一下,你把合法的元素挪到一层后,累加完,这是当前层数上一层的元素
- 记得要注意1号节点不一定是根节点,所以记得统计一下入度
代码
#include<bits/stdc++.h>
using namespace std;
const int N=1e6+10;
struct node{
int next,to;
}a[N<<1];
int n,p,q;
int ln[N],tot;
priority_queue<long long ,vector<long long>,greater<long long> > f[N];
int top[N],Bit,ru[N];
char s[N];
inline void solve(int u)
{
int t;
if(s[u]=='+') t=p;
else t=q;
while(f[u].size()>1)
{
int x1=f[u].top(); f[u].pop();
int x2=f[u].top(); f[u].pop();
f[u].push(x2+t);
}
}
void dfs(int u,int last,int fa)
{
top[u]=last;
if(!ln[u])
{
f[last].push(0);
return ;
}
for(int i=ln[u];i;i=a[i].next)
{
int v=a[i].to;
if(v<n&&s[v]!=s[u]) dfs(v,v,u);
else dfs(v,last,u);
}
if(u==last)
{
solve(u);
f[top[fa]].push(f[u].top());
}
}
inline void add(int x,int y) {a[++tot].next=ln[x]; ln[x]=tot; a[tot].to=y;}
inline int read()
{
int Num=0,f=1; char ch=getchar();
while(ch<'0'||ch>'9') {if(ch=='-') f=-1; ch=getchar();}
while(ch>='0'&&ch<='9') {Num=(Num<<1)+(Num<<3)+ch-'0'; ch=getchar();}
return Num*f;
}
int main()
{
n=read(),p=read(),q=read();
for(int i=1;i<n;i++) cin>>s[i];
for(int i=1;i<=(n-1)<<1;i++)
{
int x=read(),y=read();
add(x,y); ru[y]++;
}
for(int i=1;i<=n;i++) if(!ru[i]) Bit=i;
dfs(Bit,Bit,0);
printf("%lld",f[Bit].top());
return 0;
}