题目:一个天平表达式:[A,B],其中A和B为一个数值或又一个天平表达式。每个天平表达式代表的天平所有长度相等,故如果需要平衡,则要求两边质量相等。题目则是给出了一个天平表达式,要求计算,在给出表达式的情况下,如果要求平横,则最少需要调整几个物体。
思路:
原来是直接想要怎么改变,才能不影响父层的重量改变,后来越想越尴尬,就废了。
随后参考了大佬的思路,发现要换一种思路来想
要通过修改来使天平平衡,于是存在有砝码的质量是不会被改变的。假设在第D层的质量为M的砝码质量不需要被改变。于是不难得出此时的天平总质量为M*pow(2,D) = Sum,当有其他别的砝码的不变使得天平质量为Sum时,这些砝码的值都可以不用被改变。
于是砝码个数一定,所以 最少要调整的物体个数 = 砝码总数 - 不用改变砝码的最大值
由于用数组太奢侈,于是考虑用map来映射天平质量Sum对应的不用被修改的砝码的个数
要二刷呀这个题! 要二刷呀这个题! 要二刷呀这个题!
#include<cstdio>
#include<cmath>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<vector>
#include<sstream>
#include<map>
#include<stack>
#include<queue>
#include<set>
#include<string>
using namespace std;
typedef long long LL;
string s;
map<LL,int> save;//save[i] = j 值天平重量为i时不用改变的砝码个数为j
int sum;
void dfs(int depth,int left,int right){
if(s[left]=='['){
int q = 0;
for(int i = left+1;i<right;i++){
if(s[i]=='[') q++; //来找是否有子天平
if(s[i]==']') q--;
if(s[i]==','&&q==0){ // 此时s[i]左右边不是 子天平[ , ] 就是 砝码
dfs(depth+1,left+1,i-1);
dfs(depth+1,i+1,right-1);
}
}
}else{
LL value = 0;
for(int i = left;i<=right;i++) value = value*10 + s[i] - '0';
sum++;
save[value<<depth]++; // value<<depth <=> value*pow(2,depth)
}
}
int main(){
int T;
cin>>T;
while(T--){
save.clear();
sum = 0;
cin>>s;
dfs(0,0,s.size()-1);
int max_same = 0;
for(auto i = save.begin();i!=save.end();i++){//关键字auto 自动识别类型
max_same = max(max_same,i->second);
/*map容器的迭代器里有first和second,
i->first对应键值,i->second对应元素值*/
}
cout<<sum-max_same<<endl;
}
return 0;
}