#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
using namespace std;
vector<int> pre,in,level,val;
stack<int> st;
int n;
void find(int a,int c,int d)
{ if(a>=n||c>d) return;
int root=pre[a];
for(int i=c;i<=d;i++){
if(root==in[i]){
int temp=i;
find(a+1,c,temp-1);
find(a+temp-c+1,temp+1,d);
level.push_back(pre[a]);
}
}
}
int main()
{ int key=0;
string str;
scanf("%d\n",&n);
for(int i=1;i<=2*n;i++)
{ str.clear();
getline(cin,str);
if(str[1]=='u'){
int temp=str[5]-48;
val.push_back(temp);
pre.push_back(key);
st.push(key++);
}
else if(str[1]=='o'){
in.push_back(st.top());
st.pop();
}
}
find(0,0,n-1);
printf("%d",val[level[0]]);
for(int i=1;i<n;i++){
printf(" %d",val[level[i]]);}
system("pause");
}
这段代码始终过不了最后一个测试点(数据量N=30,复杂组合)
错误类型为 :答案错误
一开始我以为是数据量过大,系统堆栈溢出之类的错误,因为前几个测试点我都毫无悬念地通过了,我对自己的算法逻辑还是很有信心的,问题肯定不是出在逻辑上,并且我看到柳神的代码和我的思路基本相同,都是选用了vector容器来储存先序、中序的顺序,却始终没有把问题的矛盾转移到一开始的数据读取之上!
在做这道题的时候,其实一开始我就卡在了数据读取之上
对于Push X;\nPop\nPush X; 这样的数据排列 我想要一个能读取一行内的字母的 读取字母后 再对所读取的字母串进行判断之后是否再读入一个int 的方法; 而我采取的方法默认int只有一位数 因此在:=30时 int变量可能会有2位数字时便无法解决了!!!因此只需要改进一下数据读入的代码就可通过测试。
改进1:在我的代码的基础之上进行改造
基本思想:扫到了Push之后 假如X为两位数 则把temp*10之后再加上temp2
int main()
{ int key=0;
string str;
scanf("%d\n",&n);
for(int i=1;i<=2*n;i++)
{
getline(cin,str);
if(str[1]=='u'){
int temp=str[5]-48;
if(str.size()==7){
int temp2=str[6]-48;
temp=temp2+temp*10;
}
val.push_back(temp);
pre.push_back(key);
st.push(key++);
}
else if(str[1]=='o'){
in.push_back(st.top());
st.pop();
}
}
find(0,0,n-1);
printf("%d",val[level[0]]);
for(int i=1;i<n;i++){
printf(" %d",val[level[i]]);}
system("pause");
}
改进2:直接利用柳神的方法(但我还没理解cin的工作机制!,务必理解后再补上)