2.6
PTA学习数据结构之旅
树的同构
https://pintia.cn/problem-sets/15/problems/711
解法①
#include<stdio.h> #define max 12 #define Null -1 struct node { char data; int left,right; }t1[12],t2[12]; int build(struct node t[],int n) { int i,check[12]={0},root=Null; if(n) { for(i=0;i<n;i++) { char c1,c2; scanf("\n%c %c %c",&t[i].data,&c1,&c2); if(c1!='-') { t[i].left=c1-48; check[t[i].left]=1; } else t[i].left=-1; if(c2!='-') { t[i].right=c2-48; check[t[i].right]=1; } else t[i].right=-1; } for(i=0;i<n;i++) if(!check[i]) break; root=i; } return root; } int is(int r1,int r2) { if(r1==-1&&r2==-1)return 1; if (r1==-1&&r2!=-1||r1!=-1&&r2==-1) return 0; if(t1[r1].data!=t2[r2].data) return 0; if(t1[r1].left==-1&&t2[r2].left==-1)return is(t1[r1].right,t2[r2].right); if(t1[r1].right==-1&&t2[r2].right==-1)return is(t1[r1].left,t2[r2].left); if(t1[r1].left!=-1&&t2[r2].left!=-1&&t1[t1[r1].left].data==t2[t2[r2].left].data) return (is(t1[r1].left,t2[r2].left))&&(is(t1[r1].right,t2[r2].right)); else return (is(t1[r1].right,t2[r2].left))&&(is(t1[r1].left,t2[r2].right)); } int main() { int r1,r2,n1,n2; scanf("%d",&n1); r1=build(t1,n1); scanf("%d",&n2); r2=build(t2,n2); printf("%s",is(r1,r2)?"Yes":"No"); }
解法②运用向量
题中说树的同构就是左右孩子交换,那么左右孩子的ASCII值之和就是不变的,是一直相等的。
#include<iostream> #include<vector> #include<cctype> using namespace std; struct node { char a; char b; char c; }; int main() { int n1, n2; cin >> n1; vector<node>v1(n1); for (int i = 0; i < n1; i++) { cin >> v1[i].a >> v1[i].b >> v1[i].c; } cin >> n2; vector<node>v2(n2); for (int i = 0; i < n2; i++) { cin >> v2[i].a >> v2[i].b >> v2[i].c; } if (n1 == 1 && n2 == 1)//对一个节点的特判 { cout << "No"; return 0; } for (int i = 0; i < v1.size(); i++) { int value1 = 0, value2 = 0; for (int j = 0; j < v2.size(); j++) { if (v1[i].a == v2[j].a) { if (isdigit(v1[i].b)) value1 += v1[v1[i].b - '0'].a; if (isdigit(v1[i].c)) value1 += v1[v1[i].c - '0'].a; if (isdigit(v2[j].b)) value2 += v2[v2[j].b - '0'].a; if (isdigit(v2[j].c)) value2 += v2[v2[j].c - '0'].a; if (value1 != value2) { cout << "No"; return 0; } } } } cout << "Yes"; return 0; }