#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"); }
This code can never pass the last test point (data amount N=30, complex combination)
Error type: wrong answer
At first, I thought it was a mistake such as too much data and system stack overflow, because I passed the first few test points without any suspense. I am still very confident in my algorithm logic. The problem is certainly not logic, and I saw that Liu Shen's code and my thinking are basically the same. I chose vector container to store the sequence of first and middle order, but at first Finally did not transfer the contradiction of the problem to the data reading at the beginning!
When I was doing this, I was actually stuck in the data reading at the beginning
For Push X; \ nPop\nPush X; data arrangement, I want a method that can read letters in a row and then judge whether to read in an int after reading letters in a row; and the method I take defaults to only one digit of int, so when: = 30, the int variable may have two digits, it can't be solved!!! Therefore, you only need to improve the data reading code to pass the test.
Improvement 1: build on my code
Basic idea: if X is two digits after Push, add temp2 after temp*10
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"); }
Improvement 2: directly use Liu Shen's method (but I haven't understood the working mechanism of cin yet! Make sure you understand and then fill in)