poj 1635 判断树是否同构

【题意】

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

树的表示:从根节点深搜,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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值