poj 1635 判断树是否同构
2012-04-26 17:41
417 查看
【题意】
给出两棵树,判断树是否同构。
树的表示:从根节点深搜,0表示向下,1表示向上回溯,得到的01串。
【题解】
将树最小表示,排序
如何得到子树:子树的01串中0和1的数量相等。
所以只需递归求解。
【代码】
给出两棵树,判断树是否同构。
树的表示:从根节点深搜,0表示向下,1表示向上回溯,得到的01串。
【题解】
将树最小表示,排序
如何得到子树:子树的01串中0和1的数量相等。
所以只需递归求解。
【代码】
#include <iostream> #include <cstring> #include <algorithm> #include <vector> using namespace std; const int maxn=3005; struct node { char s[maxn]; int len; node() {} node(char* ts,int tlen) { for (int i=0;i<tlen;i++) s[i]=ts[i]; len=tlen; s[len]='\0'; } node(char ts) { s[0]=ts; s[1]='\0'; len=1; } }a,b; char s[maxn]; bool cmp(node a,node b) { if (a.len<b.len) return true; if (a.len>b.len) return false; for (int i=0;i<a.len;i++) if (a.s[i]<b.s[i]) return true; else if (a.s[i]>b.s[i]) return false; return true; } node& operator+ (node& a,const node &b) { strncat(a.s,b.s,b.len); a.len+=b.len; return a; } void dfs(node& x) { if (x.len<=2) return; int i,j=0,sum=0; vector<node> w; w.clear(); for (i=0;i<x.len;i++) { if (x.s[i]=='0') sum++; else sum--; if (sum==0) { w.push_back(node(&x.s[j+1],i-j-1)); j=i+1; } } for (i=0;i<w.size();i++) dfs(w[i]); sort(w.begin(),w.end(),cmp); x=node('0'); x=x+w[0]+node('1'); for (i=1;i<w.size();i++) x=x+node('0')+w[i]+node('1'); } int main() { freopen("pin.txt","r",stdin); freopen("pou.txt","w",stdout); int cc,i; bool ans; scanf("%d",&cc); while (cc--) { scanf("%s",s); a=node(s,strlen(s)); scanf("%s",s); b=node(s,strlen(s)); dfs(a); dfs(b); ans=true; for (i=0;i<a.len;i++) if (a.s[i]!=b.s[i]) { ans=false; break; } if (ans) printf("same\n"); else printf("different\n"); } return 0; }
相关文章推荐
- poj 1635 由搜索序列判断树是否同构
- POJ 1635 Subway tree systems Hash法判断有根树是否同构
- poj-1635 Subway tree systems(判断两个有根树是否同构)-哈希法
- POJ 1635 Subway tree systems(HASH+判断两棵有根树是否同构)
- poj-1635 Subway tree systems(推断两个有根树是否同构)-哈希法
- 地铁系统 POJ1635 subway tree systems 判断树同构 DFS搜索子串
- poj 1635 树同构 记录成长历程
- poj 1635( 树的最小表示法判断同构 )
- poj1635_树的同构
- poj 1635 Subway tree systems 判断树的同构 树的最大最小表示法模板
- 【有根树的同构】ZOJ 1990/POJ 1635
- poj 1635 Subway tree systems (树同构)
- POJ1635【树的同构】【hash】
- POJ 1635 Subway tree systems(树同构)
- POJ 1635 Subway tree systems (树的同构)
- 同构树的判断 poj 1635
- 树的同构--poj 1635(有根树)ustc 1117 (无根树)
- poj 1635 Subway tree systems(树的同构,经典)
- 树的同构 poj 1635
- poj 1635 Subway tree systems 判断是否是同构树