1 条题解

  • 0
    @ 2025-10-10 19:37:03

    C++ :

    #include <bits/stdc++.h>
    using namespace std;
    
    //存储树的结构数据 
    struct node{
    	int l,r,v;
    }a[1000001]; 
    
    //判断以x和y这两个结点是否对称 
    bool match(int x,int y){
    	if(x==-1&&y==-1) return true;
    	if(x==-1||y==-1) return false;//只有一个子节点,不可能对称
    	//节点权值不同 
    	if(a[x].v != a[y].v) return false; 
    	
    	return match(a[x].l,a[y].r) && match(a[x].r,a[y].l);
    } 
    
    //求节点x的子数的节点数 
    int num(int x){
    	if(x == -1) return 0;
    	else return num(a[x].l) + num(a[x].r) + 1;
    } 
    
    int main(){
    	int n,ans = 0;
    	cin>>n;
    	//读入权重 
    	for(int i = 1;i <= n;i++){
    		//cin>>a[i].v;
    		scanf("%d",&a[i].v);
    	}
    	
    	for(int i = 1;i <= n;i++){
    //		cin>>a[i].l>>a[i].r;
    		scanf("%d%d",&a[i].l,&a[i].r);
    	}
    	
    	//循环每个子树的情况求解
    	for(int i = 1;i <= n;i++){
    		if(match(a[i].l,a[i].r)){
    			ans = max(ans,num(i));
    		}
    	} 
    	
    	cout<<ans;
    	return 0;
    }
    
    
    • 1

    信息

    ID
    907
    时间
    1000ms
    内存
    512MiB
    难度
    (无)
    标签
    递交数
    0
    已通过
    0
    上传者