这道题是求树的最小表示。
从0开始到1结束,如果0的个数和1的个数相等,说明遍历了一个子树回来了。我们可以递归地处理每棵树。
首先每棵树可以按照如上的方式分解成多个子树,在递归地处理完每个子树后,我们把子树排序,然后拼接起来。任何排序应该都是可以的,只要排序后同一棵树的不同的遍历的表达形式是一样的。我们这里按照string从小到大的顺序排的。
thestoryofsnow | 1635 | Accepted | 712K | 344MS | C++ | 1574B |
/*
ID: thestor1
LANG: C++
TASK: poj1635
*/
#include <iostream>
#include <fstream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <limits>
#include <string>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#include <cassert>
using namespace std;
void toMinimalForm(string &str)
{
if (str.length() == 2)
{
return;
}
std::vector<string> substrs;
int zero = 0, start = 0, end = 0;
for (int i = 0; i < str.length(); ++i)
{
if (str[i] == '0')
{
zero++;
}
else if (str[i] == '1')
{
zero--;
if (zero == 0)
{
// new subtree (start, end)
end = i;
assert(str[start] == '0' && str[end] == '1');
string substr = str.substr(start + 1, end - 1 - start);
toMinimalForm(substr);
substrs.push_back('0' + substr + '1');
start = i + 1;
}
}
}
assert(zero == 0);
sort(substrs.begin(), substrs.end());
str = "";
for (int i = 0; i < substrs.size(); ++i)
{
str += substrs[i];
}
}
int main()
{
int T;
scanf("%d", &T);
string str1, str2;
for (int t = 0; t < T; ++t)
{
cin >> str1 >> str2;
// cout << "str1: " << str1 << endl;
// cout << "str2: " << str2 << endl;
bool isSame = true;
if (str1.length() != str2.length())
{
isSame = false;
}
else
{
toMinimalForm(str1);
toMinimalForm(str2);
// cout << "[toMinimalForm]str1: " << str1 << ", str2: " << str2 << endl;
isSame = (str1 == str2);
}
if (isSame)
{
printf("same\n");
}
else
{
printf("different\n");
}
}
return 0;
}