ACM-模拟-STL HDU1622二叉树程序遍历(路径)+map应用

样例

(11,LL) (7,LLL) (8,R)
(5,) (4,L) (13,RL) (2,LLR) (1,RRR) (4,RR) ()
(3,L) (4,R) ()
5 4 8 11 13 4 7 2 1
not complete

(a,b)括号里表示路径是b的节点值为a,()为不同的树的分隔符。
求遍历的结果,同时判断这些节点是否真的可以形成二叉树

将路径作为字符串压入map里,map查找可以更快同时简化程序。但是要自己定义这个字典序,所以用结构体node(string s,operater <)

具体代码

#include<iostream>
#include<map>
#include<string> 
using namespace std;
struct node{//结构体定义字典序
    string s;
    bool operator<(const node &q)const{
        int le=s.size(),la=q.s.size();
        if(le==la){
            int i=0;
            while(i<le){
                if(s[i]!=q.s[i])return s[i]<q.s[i];
                i++;
            }
            return false;
        }
        return le<la;
    }
};  
const int  p=10;
map<node,int>a;
string q;
bool cuo=0;
void solve(bool cuo){//结束的 
    if(!cuo){
        map<node,int>::iterator it;
        node e;
        string d;
        for(it=a.begin();it!=a.end();it++){
            d=((*it).first).s;
            if(d.size()>1){
                d.pop_back();
                e.s=d;
                if(a.find(e)==a.end()){
                    cuo=true;
                    break;
                }
            }
        }
        if(cuo)cout<<"not complete\n";
        else {
            it=a.begin();
            cout<<(*it).second;
            it++;
            for(;it!=a.end();it++)cout<<" "<<(*it).second;
            cout<<endl;

        }   
    }
    else cout<<"not complete\n";
} 
void chu(string q){//每个括号处理 
    int len=q.size(),sum=0;
    node u; 
    u.s="1";//u.s+='1';
    for(int i=0;i<len;i++){
        if(q[i]>='0'&&q[i]<='9')sum=sum*p+(q[i]-'0');
        if(q[i]=='L')u.s+='0';
        else if(q[i]=='R')u.s+='1';
    }
    if((a.size()>0&&a.find(u)!=a.end())||sum<=0)cuo=true;
    else a[u]=sum;
}
int main(){
    ios::sync_with_stdio(false);
    //freopen("1.txt","r",stdin); 
    a.clear();
    while(cin>>q){
        if(q=="()"){
            solve(cuo);
            a.clear();
            cuo=false;
            continue;
        }
        chu(q);
        string z;
        while(cin>>z){
            if(z=="()"){
                solve(cuo);
                a.clear();
                cuo=false;
                break;
            }
            chu(z);
        } 
    }
    return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值