Cod sursa(job #2225776)

Utilizator MaarcellKurt Godel Maarcell Data 28 iulie 2018 10:42:35
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.99 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
#include <set>
#include <map>
#include <cmath>
#include <cstring>
#include <ctime>
#include <unordered_map>
#include <iomanip>
#include <complex>
#include <cassert>
using namespace std;

#define fi first
#define se second
#define pb push_back
#define all(v) (v).begin(),(v).end()
#define deb(a) cerr<< #a << "= " << (a)<<"\n";

typedef long long ll;
typedef unsigned long long ull;
typedef unsigned int uint;
typedef long double ld;
typedef complex<double> base;
typedef vector<int> vi;
typedef pair<int,int> pii;

template<class T> ostream& operator<<(ostream& stream, const vector<T> v){ stream << "[ "; for (int i=0; i<(int)v.size(); i++) stream << v[i] << " "; stream << "]"; return stream; }
ll fpow(ll x, ll p, ll m){ll r=1; for (;p;p>>=1){ if (p&1) r=r*x%m; x=x*x%m; } return r;}
ll inv(ll a, ll b){ return a<2 ? a : ((a-inv(b%a,a))*b+1)/a%b; }
int gcd(int a, int b){ if (!b) return a; return gcd(b,a%b);}
ll gcd(ll a, ll b){ if (!b) return a; return gcd(b,a%b);}

char s[100100];
int p=0,N;

int eval(char *s, int &p);
int termen(char *s, int &p);
int factor(char *s, int &p);

int eval(char *s, int &p){
	int x=termen(s,p);
	
	
	while (p<N && (s[p]=='+' || s[p]=='-')){
		char op=s[p];
		
		p++;
		int y=termen(s,p);
		
		if (op=='+') x+=y;
		else x-=y;
	}
	
	return x;
}

int termen(char *s, int &p){
	int x=factor(s,p);
	
	while (p<N && (s[p]=='*' || s[p]=='/')){
		char op=s[p];
		
		p++;
		int y=factor(s,p);
		
		if (op=='*') x*=y;
		else x/=y;
	}
	
	return x;
}

int factor(char *s, int &p){
	if (s[p]=='('){
		p++;
		int res=eval(s,p);
		p++;
		return res;
	}
	else if (isdigit(s[p])){
		int x=0;
		for (; p<N && isdigit(s[p]); p++)
			x=x*10+s[p]-'0';
			
		return x;
	}
	else if (s[p]=='-'){
		p++;
		return -factor(s,p);
	}
}
 
int main(){
	ios::sync_with_stdio(0);
	cin.tie(0);
	freopen("evaluare.in","r",stdin);
	freopen("evaluare.out","w",stdout);
	
	scanf("%s",s);
	N=strlen(s);
	printf("%d\n",eval(s,p));
	
	return 0;
}