题目链接

如何判断两个树是不是同构:求出每个树的最小表示。即与这棵树同构的最小的dfs序。如果两个树同构,那么这两个树的最小表示 应该相同。 求树的最小表示可以递归实现,求出所有子树的dfs序,然后从小到大排序拼接起来

#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;

//递归返回当前节点的字符串
string dfs(string &seq, int &u)
{
    u ++ ;
    vector<string> seqs;
    while (seq[u] == '0') seqs.push_back(dfs(seq, u));
    u ++ ;
    sort(seqs.begin(), seqs.end());
    string res = "0";
    for (auto &s : seqs) res += s;
    res += '1';
    return res;
}

int main(){

    int t;
    cin>>t;
    while(t--){
        string a,b;
        cin>>a>>b;
        a='0'+a+'1';
        b='0'+b+'1';
        int ua=0,ub=0;
        auto ra=dfs(a,ua);
        auto rb=dfs(b,ub);
        if(ra == rb) cout<<"same"<<endl;
        else cout<<"different"<<endl;
    }
    return 0;
}

 posted on 2019-08-08 19:57  谁是凶手1703  阅读(44)  评论(0)    收藏  举报