想法题,然而我看了题解才知道怎么写。。。。思路是选取一个点作为基准点。用这个点及其高度计算出天平的总质量。no_change[w]表示当树的总质量为w时,不需要修改的点的个数(每选取一个基准点,其值为i,i的高度为d,那么此时树的总质量为w=i*(1<<d),于是我们知道当树的总质量为w时,这个点是不需要变动的。所以no_change[w]+1即可)。那么我们记录下所有可能的树的总质量与树的叶节点个数cnt,最终的结果就是cnt-"no_change的最大值“”。需要注意的是结点的重量最大为10^9(取不到10^9)而树的高度最大为16层,那么树的总质量可能会达到10^9*(2^16)显然用int是存不下的,得用longlong。
没必要建树,只需要记录每个叶节点的重量与高度即可,每碰到一个‘[’高度+1,碰到一个‘']’高度减一。
AC代码如下。
#include <cstdio>
#include <algorithm>
#include <map>
#include <vector>
using namespace std;
typedef long long ll;
vector<ll> sum;
map<ll,int> no_changes;
int cnt=0;
int main()
{
int T;
scanf("%d", &T);
getchar();
while(T--)
{
char c;
int d=0;
ll num=0;
int cnt=0;
sum.clear();
no_changes.clear();
while((c=getchar())!='\n')
{
if(c=='[')
{
num=0;
d++;
}
else if(c==']')
{
if(num!=0)
{
cnt++;
ll sum_w=num*(1<<d);
sum.push_back(sum_w);
if(!no_changes.count(sum_w))
no_changes[sum_w]=1;
else
no_changes[sum_w]+=1;
num=0;
}
d--;
}
else if(c==',')
{
if(num!=0)
{
cnt++;
ll sum_w=num*(1<<d);
sum.push_back(sum_w);
if(!no_changes.count(sum_w))
no_changes[sum_w]=1;
else
no_changes[sum_w]+=1;
num=0;
}
continue;
}
else
{
num=num*10+c-'0';
}
}
int maxx=-1;
if(sum.size()>0)
{
for(int i=0;i<sum.size();i++)
{
maxx=max(maxx,no_changes[sum[i]]);
}
}
else
maxx=cnt;
printf("%d\n", cnt-maxx);
}
return 0;
}