Posted: Sun Jul 23, 2006 5:59 pm
I also got WA in this problem.
Code: Select all
#include<stdio.h>
#include<string.h>
#include<ctype.h>
char s[50000];
int next(int i)
{
while(s[i]!=')')
{
i++;
}
i--;
return i;
}
char convert(char c)
{
if(c=='+')
{
return 'p';
}
else if(c=='-')
{
return 's';
}
else if(c=='*')
{
return 'm';
}
else if(c=='/')
{
return 'd';
}
else if(c=='p')
{
return '+';
}
else if(c=='s')
{
return '-';
}
else if(c=='m')
{
return '*';
}
else if(c=='d')
{
return '/';
}
else
{
return 0;
}
}
void push(int pos,int c)
{
int i=strlen(s)+1;
while(i>pos)
{
s[i]=s[i-1];
i--;
}
s[pos]=c;
return;
}
void find_back_n_push(int pos,int c)
{
int i=pos-1,sum=0;
while(i)
{
if(s[i]==')')
{
sum++;
}
else if(s[i]=='(')
{
sum--;
}
if(sum==0)
{
break;
}
i--;
}
push(i,'(');
return;
}
void find_front_n_push(int pos,int c)
{
int i=pos+1,sum=0;
while(s[i])
{
if(s[i]==')')
{
sum++;
}
else if(s[i]=='(')
{
sum--;
}
if(sum==0)
{
break;
}
i++;
}
push(i+1,convert(c));
push(i+2,')');
return;
}
int Evaluate(int b,int l)
{
int i,r=0,rsum=0;
for(i=b;i<=l;i+=(r+1))
{
r=0;
if(s[i]=='(')
{
r=Evaluate(i+1,next(i));
}
rsum+=r;
l+=r;
}
r=0;
for(i=b;i<=l;)
{
if(s[i]=='*' || s[i]=='/')
{
char c=s[i];
find_back_n_push(i,c);
find_front_n_push(i+1,c);
i+=1;
s[i]=' ';
r+=3;
rsum+=3;
l+=3;
}
i++;
}
for(i=b;i<=l;)
{
if(s[i]=='+' || s[i]=='-')
{
char c=s[i];
find_back_n_push(i,c);
find_front_n_push(i+1,c);
i+=1;
s[i]=' ';
r+=3;
rsum+=3;
l+=3;
}
i++;
}
return rsum;
}
void print()
{
int i=0;
while(s[i])
{
if(s[i]>='0' && s[i]<='9')
{
printf("%c",s[i]);
}
if(isalpha(s[i]))
{
printf("%c",convert(s[i]));
}
i++;
}
printf("\n");
return;
}
int main(void)
{
char temp[10];
int test;
scanf("%d",&test);
gets(temp);
gets(temp);
while(test--)
{
strcpy(s,"");
while(1)
{
if(!gets(temp))
{
break;
}
if(strcmp(temp,"")==0)
{
break;
}
strcat(s,temp);
}
int l=strlen(s);
// s[l]='\0';
int vua=Evaluate(0,l-1);
print();
if(test)
{
printf("\n");
}
}
return 0;
}
Code: Select all
11
3
+
4
*
2
3
*
4
+
2
(
3
+
4
)
*
2
3
*
(
4
+
2
)
(
3
+
4
)
*
(
4
+
5
)
3
+
4
-
5
(
3
+
2
)
*
5
(
5
+
(
5
+
5
)
)
(
1
)
(
1
/
2
*
3
+
4
)
5
(
(
2
)
)
Code: Select all
342*+
34*2+
34+2*
342+*
34+45+*
34+5-
32+5*
555++
1
12/3*4+5*
2
Code: Select all
1
(
3
+
(
3
+
2
)
*
(
4
+
5
+
2
)
*
(
1
+
2
-
3
/
(
1
-
2
*
(
4
+
4
)
)
)
)
-
3
*
5
Code: Select all
332+45+2+*12+31244+*-/-*+35*-
Code: Select all
CODE ACCEPTED
Code: Select all
2
(
3
+
2
)
*
5
(
3
+
2
)
*
5
Code: Select all
32+5*
32+5*
Code: Select all
CODE WAS ACCEPTED
Code: Select all
Code has been cut after a.c.
The problem is one the line
gets(input);
I have cut this line and got accepted. Thanks Jan vai for his help.
Code: Select all
3
4
+
4
*
2
5
-
1
/
2
6
/
2
Code: Select all
442*+
512/-
62/