zoukankan      html  css  js  c++  java
  • 树的同构

    import java.util.*;
    class treenode{
     public char val;
     int left;
     int right;
    }
    public class Main {
     public static int root = -1; //全局变量
     public static treenode[] buildtree(Scanner in){
      treenode[] T = new treenode[10];
      int N = in.nextInt();
            if(N == 0) return null;//空树判断
      int[] check = new int[N];
      for(int i=0;i<N;i++) {
       T[i] = new treenode();//新建结点
       T[i].val = in.next().charAt(0);
       char cl = in.next().charAt(0);//left
       if(cl!='-') {
        T[i].left = cl-'0';
        check[T[i].left]=1;
       }
       else  T[i].left = -1;
       char cr = in.next().charAt(0);//right
       if(cr!='-') {
        T[i].right = cr-'0';
        check[T[i].right]=1;
       }
       else  T[i].right = -1;
       
      }
      int j;
      for(j=0;j<N;j++) {
       if(check[j] == 0) break;
      }
      root = j;
      return T;
      
     }
     static boolean istg(int r1,int r2,treenode[] T1,treenode[] T2 ) {
      if(r1 == -1 && r2 == -1) return true;
      if((r1 == -1 && r2 != -1)||(r2 == -1 && r1 != -1)) return false;
      if(T1[r1].val != T2[r2].val) return false;
      if(T1[r1].left == -1 && T2[r2].left == -1)
       return istg(T1[r1].right,T2[r2].right,T1,T2);
      if(T1[r1].left != -1 && T2[r2].left != -1 && T1[T1[r1].left].val == T2[T2[r2].left].val)
       return (istg(T1[r1].left,T2[r2].left,T1,T2) && istg(T1[r1].right,T2[r2].right,T1,T2));
      else return (istg(T1[r1].left,T2[r2].right,T1,T2) && istg(T1[r1].right,T2[r2].left,T1,T2));
      
      
     }
     public static void main(String[] args) {
      Scanner in = new Scanner(System.in);
      
      treenode[] T1 = buildtree(in);
      int r1 = root;
      treenode[] T2 = buildtree(in);
      int r2 = root;
      if(istg(r1,r2,T1,T2))
      System.out.println("Yes");
      else System.out.println("No");
      
      
     }
    }

    注意:

    只能在main函数里定义scanner in,再传给其他函数,否则会出现读数据出错。

  • 相关阅读:
    【hdu 4135】Co-prime
    【cdoj 1544】当咸鱼也要按照基本法
    【SRM 717 DIV2 C】DerangementsDiv2
    【codeforces 821E】Okabe and El Psy Kongroo
    【SRM 717 div2 B】LexmaxReplace
    【SRM 717 div2 A】 NiceTable
    Network architecture for minimalistic connected objects
    C# 委托的理解
    50条超精辟的经典语录:哗众,可以取宠,也可以失宠!
    50条超精辟的经典语录:哗众,可以取宠,也可以失宠!
  • 原文地址:https://www.cnblogs.com/dyq19/p/10741240.html
Copyright © 2011-2022 走看看