题目大意:给定一个深度不超过16的二叉树,代表一个天平,问至少修改多少个秤砣,才能使天平平衡。
题目意思很简单,就是找一个可以使整个天平修改次数最少的点,一个点可以确定整个天平,开始我就用的这个思路,会超时。
方法:利用二叉树的特性,找出重复最多的点,深度会改变节点值,深度是假如深度是n的话,value=nowvalue<<n,用map储存,每次加一。寻找出重复最多的,然后用总节点数-重复最多的节点数。dfs遍历左右两节点,循环遍历。
代码:
#include<iostream>
#include <string>
#include <string.h>
#include <algorithm>
#include<map>
#include<vector>
using namespace std;
map<long long, int>mt;
string s;int sum=0;
void dfs(int depth, int s1, int e1) {
if (s[s1] == '[') {
int p = 0;
for (int i = s1 + 1; i !=e1; ++i) {
if (s[i] == '[')++p;
if (s[i] == ']')--p;
if (p == 0 && s[i] == ',') {
dfs(depth + 1, s1 + 1, i - 1);
dfs(depth + 1, i + 1, e1 - 1);
}
}
}
else {
long long w=0;
for (int i = s1; i <= e1; ++i) { w = w * 10 + s[i] - '0'; }
++mt[w << depth]; ++sum;
}
}
int main()
{
int kase = 0;
cin >> kase;
while (kase-- > 0) {
cin >> s;
mt.clear(); int maxn = 0; sum = 0;
dfs(0, 0, s.length() - 1);
for (map<long long, int>::iterator it = mt.begin(); it != mt.end(); ++it) {
maxn = max(maxn, (*it).second);
}
cout << sum - maxn << endl;
}
//system("pause");
return 0;
}