B is not a subtree of any tree.
Recommendation index :※
Source: http://ac.jobdu.com/problem.php? PID = 1, 1520
The algorithm itself is difficult. Pay attention to the following points:
1. Be careful when using the vector and time out ..
2. The default subtree condition of the question is: None, left and right. Don't think it's complicated.
#include<iostream>#include<string.h>#include <stdio.h>#include<stdlib.h>using namespace std;const int N=1001;int a_edge[N][2],b_edge[N][2];int a_val[N],b_val[N];int n,m;bool dfs_sub(int a,int b){//sub tree is fitif(b==0) return true;if(a_val[a]!=b_val[b]||false==dfs_sub(a_edge[a][0],b_edge[b][0])||false==dfs_sub(a_edge[a][1],b_edge[b][1]))return false;return true;}bool is_sub(){ int i;for(i=1;i<=n;i++){if(a_val[i]==b_val[1]){if(true==dfs_sub(i,1))return true;}}return false;}int main(){ while(scanf("%d%d",&n,&m)!=EOF){memset(a_val,0,sizeof(a_val));memset(b_val,0,sizeof(b_val)); int i,j,num;for(i=1;i<=n;i++)scanf("%d",&a_val[i]);for(i=1;i<=n;i++){scanf("%d",&num);for(j=0;j<num;j++)scanf("%d",&a_edge[i][j]);}for(i=1;i<=m;i++)scanf("%d",&b_val[i]);for(i=1;i<=m;i++){int num,tmp;scanf("%d",&num);for(j=0;j<num;j++)scanf("%d",&b_edge[i][j]);}if(m!=0&&n!=0&&true==is_sub())printf("YES\n");elseprintf("NO\n"); } return 0;}
In the version with the last case timeout of a vector attached:
#include<iostream>#include<vector>#include<string>#include <stdio.h>#include<stdlib.h>using namespace std;vector<vector<int> > a_edge;vector<vector<int> > b_edge;int *a_val,*b_val;int n,m;bool dfs_sub(int a_node,int b_node){//sub tree is fit if(a_val[a_node]==b_val[b_node]){if(b_edge[b_node].size()<a_edge[a_node].size()){int i,j;if(b_edge[b_node].size()==0) return true;else{ if(dfs_sub(a_edge[a_node][0],b_edge[b_node][0])==true)return true; } }else if(b_edge[b_node].size()==a_edge[a_node].size()){int i;bool flag=false;for(i=0;i<b_edge[b_node].size();i++){if(false==dfs_sub(a_edge[a_node][i],b_edge[b_node][i]))return false;}return true;} } return false;}bool is_sub(){ int i;for(i=1;i<=n;i++){if(a_val[i]==b_val[1]){if(true==dfs_sub(i,1))return true;}}return false;}int main(){ while(scanf("%d%d",&n,&m)!=EOF){ a_val=new int [n+1]; b_val=new int [m+1]; a_edge.resize(n+1); b_edge.resize(m+1); int i,j;for(i=1;i<=n;i++)scanf("%d",&a_val[i]);for(i=1;i<=n;i++){int num,tmp;scanf("%d",&num);for(j=1;j<=num;j++){scanf("%d",&tmp);a_edge[i].push_back(tmp);}}for(i=1;i<=m;i++)scanf("%d",&b_val[i]);for(i=1;i<=m;i++){int num,tmp;scanf("%d",&num);for(j=1;j<=num;j++){scanf("%d",&tmp);b_edge[i].push_back(tmp);}}if(m!=0&&n!=0&&true==is_sub())printf("YES\n");elseprintf("NO\n"); } return 0;}