1 #include<iostream> 2 #include<cmath> 3 #include<algorithm> 4 using namespace std; 5 struct stack 6 { 7 long value[100010]; 8 bool dir[100010]; 9 long size = 0; 10 }; 11 void push(stack &one, long m_value, bool m_dir) 12 { 13 one.value[one.size] = m_value; 14 one.dir[one.size] = m_dir; 15 one.size++; 16 } 17 void pop(stack &one) 18 { 19 one.size--; 20 } 21 long get_value(stack &one)//注意这里,栈顶元素的value的下标应该是size-1,而不是size 22 { 23 return one.value[one.size-1]; 24 } 25 bool get_dir(stack &one) 26 { 27 return one.dir[one.size-1];//注意这里,栈顶元素的dir的下标应该是size-1,而不是size 28 } 29 bool empty(stack &one) 30 { 31 if (one.size == 0) return true;//当栈中无元素时,返回true 32 else return false;//有元素时,返回false 33 } 34 long size(stack &one) 35 { 36 return one.size; 37 } 38 void handle(stack &one, long &m_value, bool &m_dir)//处理要放进的元素方向是0,而栈中的元素方向是1时的情况 39 { 40 if (empty(one)) push(one, m_value, m_dir); 41 else if (get_dir(one) == false) push(one, m_value, m_dir);//当栈顶元素的方向是0的时候,放入元素,结束递归 42 else 43 { 44 if (m_value > get_value(one)) { pop(one); handle(one, m_value, m_dir); }//新元素大于栈顶元素时,pop后递归 45 else return;//新元素小于栈顶元素时,不放入 46 } 47 } 48 int main() 49 { 50 stack one; 51 long n, m_value; 52 bool m_dir; 53 cin >> n >> m_value >> m_dir; 54 push(one, m_value, m_dir); 55 for (long i = 1; i < n; i++) 56 { 57 cin >> m_value >> m_dir; 58 if (m_dir == true) push(one, m_value, m_dir); 59 else if (get_dir(one) == false) push(one, m_value, m_dir); 60 else handle(one, m_value, m_dir); 61 } 62 cout << size(one) << endl; 63 system("pause"); 64 return 0; 65 }
时间: 2024-11-02 19:31:56