标签:
给定两个有根树的dfs序,问这两棵树是否同构
题解:http://blog.sina.com.cn/s/blog_a4c6b95201017tlz.html
题目要求判断两棵树是否是同构的,思路是用树的最小表示法去做。这里用的最小表示法就是将树的所有子树分别用1个字符串表示,要按字典序排序将他们依依连接起来。连接后如果两个字符串是一模一样的,那么他们必然是同构的。这样原问题就变成了子问题,子树又是一颗新的树。
1 Source Code 2 Problem: 1635 User: sdfzyhy 3 Memory: 1160K Time: 672MS 4 Language: G++ Result: Accepted 5 6 Source Code 7 8 //PKUSC 2013 R1 C 9 #include<string> 10 #include<vector> 11 #include<cstdio> 12 #include<cstring> 13 #include<cstdlib> 14 #include<iostream> 15 #include<algorithm> 16 #define rep(i,n) for(int i=0;i<n;++i) 17 #define F(i,j,n) for(int i=j;i<=n;++i) 18 #define D(i,j,n) for(int i=j;i>=n;--i) 19 #define pb push_back 20 using namespace std; 21 typedef long long LL; 22 inline int getint(){ 23 int r=1,v=0; char ch=getchar(); 24 for(;!isdigit(ch);ch=getchar()) if (ch==‘-‘) r=-1; 25 for(; isdigit(ch);ch=getchar()) v=v*10-‘0‘+ch; 26 return r*v; 27 } 28 const int N=3010; 29 /*******************template********************/ 30 string s1,s2; 31 32 string dfs(string s){ 33 vector<string>a; 34 string ans=""; 35 int t=0,st=0; 36 rep(i,s.length()){ 37 if (s[i]==‘0‘) t++; 38 else t--; 39 if (t==0){ 40 if (i-1 > st+1){ 41 a.pb("0"+dfs(s.substr(st+1,i-1-st))+"1"); 42 }else a.pb("01"); 43 st=i+1; 44 } 45 } 46 sort(a.begin(),a.end()); 47 rep(i,a.size()) ans=ans+a[i]; 48 return ans; 49 } 50 51 int main(){ 52 #ifndef ONLINE_JUDGE 53 freopen("C.in","r",stdin); 54 freopen("C.out","w",stdout); 55 #endif 56 int T=getint(); 57 while(T--){ 58 cin >> s1 >> s2; 59 if (dfs(s1)==dfs(s2)) puts("same"); 60 else puts("different"); 61 } 62 return 0; 63 }
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 7060 | Accepted: 2935 |
Description
Input
Output
Sample Input
2 0010011101001011 0100011011001011 0100101100100111 0011000111010101
Sample Output
same different
Source
[Submit] [Go Back] [Status] [Discuss]
【POJ】【1635】Subway Tree Systems
标签:
原文地址:http://www.cnblogs.com/Tunix/p/4534372.html