POJ1635 Subway tree systems ——(判断树的同构,树的最小表示法)

  给两棵有根树,判断是否同构。因为同构的树的最小表示法唯一,那么用最小表示法表示这两棵树,即可判断同构。顺便如果是无根树的话可以通过选出重心以后套用之前的方法。

  AC代码如下:

 1 #include <stdio.h>
 2 #include <algorithm>
 3 #include <string.h>
 4 #include <string>
 5 #include <iostream>
 6 #include <vector>
 7 using namespace std;
 8 
 9 string str1, str2;
10 
11 string min_pre(string str){
12       vector<string> box;
13       string ret = "";
14       int equal = 0, st = 0;
15       for(int i = 0; i < str.size(); i++){
16            if(str[i] == '0') equal++;
17            else equal--;
18            if(equal == 0){
19                 if(i - 1 > st + 1){
20                     box.push_back("0" + min_pre(str.substr(st + 1,i - 1 - st)) + "1");
21                 }else box.push_back("01");
22                 st = i + 1;
23            }
24       }
25       sort(box.begin(), box.end());
26       for(int i = 0; i < box.size(); i++) ret += box[i];
27       return ret;
28 }
29 
30 int main(){
31       int ca;
32       scanf("%d", &ca);
33       while(cin >> str1 >> str2){
34            if(min_pre(str1) == min_pre(str2)) printf("same
");
35            else printf("different
");
36       }
37 }

  另外,如果是问a树是否是b树的子树,只要用kmp判断a的最小表示法是不是b的最小表示法的子串即可。

原文地址:https://www.cnblogs.com/zzyDS/p/7657162.html