题意
传送门 POJ 1635 Subway tree systems
题解
判断不同 D F S DFS DFS 序对应的有根树是否相同。设字符串长度为 N N N, O ( N 2 ) O(N^2) O(N2) 求解树的最小表示, O ( N ) O(N) O(N) 进行比较。
树的最小表示法基本思路:由于树根的确定,若两颗树同构,那么只有子树和子树中节点次序上的区别。递归与回溯是一一对应的,所以子树的 D F S DFS DFS 序满足 0 , 1 0,1 0,1 个数相等。按照字典序使子树有序,递归求解即可。
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
string solve(string s)
{
if (!s.size())
return "";
vector<string> v;
int cnt = 0, pre = 0;
for (int i = 0; i < (int)s.size(); ++i)
{
cnt += s[i] == '0' ? 1 : -1;
if (!cnt)
{
v.push_back("0" + solve(s.substr(pre + 1, i - pre - 1)) + "1");
pre = i + 1;
}
}
sort(v.begin(), v.end());
string res = "";
for (int i = 0; i < (int)v.size(); ++i)
res += v[i];
return res;
}
int main()
{
int t;
string a, b;
scanf("%d", &t);
while (t--)
{
cin >> a >> b;
puts(solve(a) == solve(b) ? "same" : "different");
}
return 0;
}