POJ 3437 Tree Grafting

题意:给出一个深度优先遍历树的up down顺序,求这棵树以及这棵树变为”左子右兄”树的高度

思路:直接dfs,x代表树1的高度,y代表树2的高度

#include<cstdio>
#include<cmath>
#include<cstring>
#include<iostream>
#include<algorithm>
int h1=0,h2=0,u=0;
char s[200005];
int read(){
    char ch=getchar();int f=1,t=0;
    while (ch<'0'||ch>'9') {if (ch=='-') f=-1;ch=getchar();}
    while ('0'<=ch&&ch<='9'){t=t*10+ch-'0';ch=getchar();}
    return t*f;
}
void dfs(int x,int y){
    int son=0;
    while (s[u]=='d'){
        u++;son++;
        dfs(x+1,y+son);
    }
    u++;
    h1=std::max(h1,x);
    h2=std::max(h2,y);
}
int main(){
    int T=0;
    scanf("%s",s);
    while (s[0]!='#'){
        h1=h2=u=0;
        dfs(0,0);
        printf("Tree %d: %d => %d
",++T,h1,h2);
        scanf("%s",s);
    }
}
原文地址:https://www.cnblogs.com/qzqzgfy/p/5577060.html