想法題,然而我看了題解才知道怎麼寫。。。。思路是選取一個點作爲基準點。用這個點及其高度計算出天平的總質量。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;
}