Mai intai trebuie sa te autentifici.
Cod sursa(job #201845)
Utilizator | Data | 4 august 2008 12:17:32 | |
---|---|---|---|
Problema | Bool | Scor | 30 |
Compilator | cpp | Status | done |
Runda | Arhiva de probleme | Marime | 3.35 kb |
#include <stdio.h>
#include <string.h>
#define FALSE 0
#define TRUE 1
#define LPAR 11
#define RPAR 12
#define NOT 21
#define AND 22
#define OR 23
int N;
int i,j;
int out[512],ops[512]; //shunting yard issues
int stack[512]; //RPN issues
bool val[32]; //variables values
char txt[1024],crt,aux; //input
int main(){
freopen("bool.in","r",stdin);
freopen("bool.out","w",stdout);
gets(txt);
//check http://en.wikipedia.org/wiki/Shunting_yard_algorithm
for( i=0; i<strlen(txt); ++i )
{
crt=txt[i];
if( crt == ' ' ) ;
//token is a variable
else if( crt >= 'A' && crt <= 'Z' && ( txt[i+1]==' ' || txt[i+1] == ')' ) )
out[++out[0]] = crt-'A'+100;
//token is "TRUE"
else if( crt == 'T' && txt[i+1] == 'R' )
{
out[++out[0]] = TRUE;
i += 3;
}
//token is "FALSE"
else if( crt == 'F' && txt[i+1] == 'A')
{
out[++out[0]] = FALSE;
i += 4;
}
//token is a left parenthesis
else if( crt == '(' )
ops[++ops[0]] = LPAR;
//token is "NOT"
else if( crt == 'N' )// && txt[i+1] == 'O' )
{
ops[++ops[0]] = NOT;
i += 2;
}
//token is "AND"
else if( crt == 'A' )// && txt[i+1] == 'N')
{
while( ops[ops[0]] == AND || ops[ops[0]] == OR )
{
out[++out[0]] = ops[ops[0]];
--ops[0];
}
ops[++ops[0]] = AND;
i += 2;
}
//token is "OR"
else if( crt == 'O' )// && txt[i+1] =='R' )
{
while( ops[ops[0]] == OR)
{
out[++out[0]] = ops[ops[0]];
--ops[0];
}
ops[++ops[0]] = OR;
++i;
}
//token is a right parenthesis
else if( crt == ')' )
{
while(ops[ops[0]] != LPAR)
{
out[++out[0]] = ops[ops[0]];
--ops[0];
}
--ops[0]; //the left parenthesis
if(ops[ops[0]] == NOT)
{
out[++out[0]] = NOT;
--ops[0];
}
}
}
//pop the remaining operators off the stack
while( ops[0] )
{
out[++out[0]] = ops[ops[0]];
--ops[0];
}
//the end of the shunting yard algorithm
//check this link for RPN: http://en.wikipedia.org/wiki/Reverse_Polish_notation
scanf("%d\n",&N);
for( ; N; --N )
{
scanf("%c",&aux);
val[aux-'A'] = (val[aux-'A'])?0:1;
for( i = 1; i<=out[0]; ++i )
{
//variable
if( out[i] > 99)
stack[++stack[0]] = val[out[i]-100];
//TRUE & FALSE
else if( out[i] < 2 )
stack[++stack[0]] = out[i];
//NOT
else if( out[i] == NOT )
stack[stack[0]] = (stack[stack[0]])?0:1;
//AND
else if( out[i] == AND)
{
stack[stack[0]-1] = (stack[stack[0]]==1 && stack[stack[0]-1]==1)?1:0;//stack[stack[0]] & stack[stack[0]-1];
stack[0]--;
}
//OR
else if( out[i] == OR)
{
stack[stack[0]-1] = (stack[stack[0]] || stack[stack[0]-1])?1:0;//stack[stack[0]] | stack[stack[0]-1];
stack[0]--;
}
}
printf("%d",stack[1]);
stack[0]=0;
}
}