今天做了一道判定树同构的题。由于其是有根树,我们可以将这棵树用最小字典序表示出进行比较即可,找最小序的过程用递归完成即可。另外用string表示的过程中,可以采用std::ios::sync_with_sdtio(false)来提高输入效率(虽然也只是十几ms级别,离大神们的0ms还是有很长路要走。。另外看他们用hash方法能够取得接近0ms的成绩,或许我还要学习一个)
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <algorithm>
#include <iostream>
#include <vector>
#include <cstdio>
using namespace std;
int n;
class subwayTree
{
public:
subwayTree() { std::ios::sync_with_stdio(false); cin>>treeNodes; }
bool operator == (subwayTree B)
{
if (treeNodes.length() != B.length())
return false;
return standardString() == B.standardString();
}
int length() { return treeNodes.length(); }
string standardString() { return parse(treeNodes); }
string parse(string a)
{
vector<string > tempParse;
tempParse.clear();
int sum = 0, start = 0;
for (int i = 0; i < a.length(); i++) {
if (a[i] == '0')
sum++;
else
sum--;
if (sum == 0) {
if (i - start == 1)
tempParse.push_back("01");
else {
string temp = "0" + parse(a.substr(start + 1, i - start - 1)) + "1";
tempParse.push_back(temp);
}
start = i + 1;
}
}
sort(tempParse.begin(), tempParse.end());
string ret;
for (int i = 0; i < tempParse.size(); i++)
ret += tempParse[i];
tempParse.clear();
return ret;
}
private:
string treeNodes;
};
int main()
{
scanf("%d", &n);
getchar();
for (int i = 0; i < n; i++) {
subwayTree A = subwayTree();
subwayTree B= subwayTree();
if (A == B)
printf("same\n");
else
printf("different\n");
}
}