Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.7 kB
2
Indexable
Never
#include<iostream>
using namespace std;

int uu_tien(char c)
{
	if(c=='+'||c=='-')
		return 1;
	if(c=='*'||c=='/'||c=='%')
		return 2;
	
	return 0;
}

int main(){
	for(int tc =1; tc <=10; tc++){
		char a[150];
		int m;
		cin >> m;

		for(int i =0; i<m; i++){
			cin >> a[i];
		}


		char b[150],c[150]; //b la chuoi kq, c la chuoi chua cac ky tu la toan tu
		int top=-1,n=-1;  
		for(int i=0;i < m;i++) //quet tu dau len
		{
			if('0'<=a[i]&&a[i]<='9') //neu la toan hang cho vao b
			{
					n++;
					b[n]=a[i];
			}
			if(a[i]=='(') //neu la '(' cho vao c
			{
				top++;
				c[top]=a[i];
			}
		
			if(a[i]==')') 
				{
					do
					{
						n++;  //neu la ')' thi lan luot cho nhung toan tu trong c vao b cho den khi gap '('
						b[n]=c[top]; 
						top--;
					}while(c[top]!='(');
					top--; //bo dau '('
				}
			if(a[i]=='+' || a[i]=='*')
				{
					while(uu_tien(c[top]) >= uu_tien(a[i]))   //if (toan tu cuoi cung trong c co do uu tien lon hon hoac bang toan tu dang duyet
					{        
					n++;
					b[n]=c[top];     //thi cho toan tu do vao b-kq
					top--;
					}
					top++; 
					c[top]=a[i]; //cho toan tu dang duyet vao c
				}				
			}
		

 if(top>-1)
 {
  for(int i=top;i>=0;i--){ //sau khi duyet het ma trong c van con phan tu thi lan luot cho vao b
   n++;
   b[n]=c[i];
  }
 }
 int kqua[150];
 int k=-1;
 for(int i=0;i<=n;i++){ 
	if('0'<=b[i] && b[i]<='9'){
		k++;
		kqua[k] = b[i] - 48;
	}
	if(b[i]=='*'){
		kqua[k-1] = kqua[k]*kqua[k-1];
		kqua[k] =0;
		k--;
	}
	if(b[i]=='+'){
		kqua[k-1] = kqua[k]+kqua[k-1];
		kqua[k] =0;
		k--;
	} 
	}
 cout << "#" << tc <<" " << kqua[0]<<endl;
	}
 return 0;
}