您的位置:首页 > 其它

poj 1635 判断树是否同构

2012-04-26 17:41 417 查看
【题意】

给出两棵树,判断树是否同构。

树的表示:从根节点深搜,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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: